Home  >  Article  >  Web Front-end  >  JSON data format

JSON data format

高洛峰
高洛峰Original
2016-12-17 14:58:441170browse

Basic structure

JSON is built on two structures:

1. A collection of name/value pairs. In different languages, it is understood as an object, a record, a struct, a dictionary, a hash table, a keyed list, or an associative array. array).

2. An ordered list of values. In most languages, it is understood as an array.

Basic Example

Simply put, JSON can convert a set of data represented in a JavaScript object into a string, and then you can easily pass this string between functions, or convert characters in an asynchronous application The string is passed from the Web client to the server-side program. This string looks a little weird, but JavaScript can easily interpret it, and JSON can represent more complex structures than "name/value pairs". For example, arrays and complex objects can be represented rather than just simple lists of keys and values.

Represents a name/value pair

In its simplest form, a "name/value pair" can be represented by the following JSON: { "firstName": "Brett" }

This example is very basic and actually Takes up more space than the equivalent plain text name/value pair: firstName=Brett

However, JSON comes into its own when multiple name/value pairs are strung together. First, you can create a record containing multiple "name/value pairs", such as:

{ "firstName": "Brett", "lastName": "McLaughlin", "email": "aaaa" }

From a syntax perspective At first glance, this isn't a huge advantage over name/value pairs, but in this case JSON is easier to use and more readable. For example, it makes it clear that the above three values ​​are part of the same record; the curly braces make the values ​​somehow related.

Representing an array

When it is necessary to represent a set of values, JSON can not only improve readability, but also reduce complexity. For example, suppose you want to represent a list of people's names. In XML, many start and end tags are required; if you use typical name/value pairs (like the ones you saw in previous articles in this series), a proprietary data format must be created , or change the key name to the form person1-firstName.

If using JSON, just group multiple records together with curly braces:

{ "people": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"},
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
]}

This is easy to understand. In this example, there is only one variable called people, and the value is an array of three entries, each entry being a record for a person containing a first name, last name, and email address. The above example demonstrates how to use parentheses to combine records into a single value. Of course, multiple values ​​(each containing multiple records) can be represented using the same syntax:

{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
] }

The most notable thing here is the ability to represent multiple values, each of which in turn contains multiple values. However, it should also be noted that the actual name/value pairs in the record can differ between different main entries (programmers, authors, and musicians). JSON is fully dynamic, allowing the way data is represented to change in the middle of the JSON structure.

There are no predefined constraints that need to be followed when processing data in JSON format. Therefore, within the same data structure, the way the data is represented can be changed, and the same thing can even be represented in different ways.

Format Application

After mastering the JSON format, using it in JavaScript is very simple. JSON is a native JavaScript format, which means that processing JSON data in JavaScript does not require any special API or toolkit.

Assigning JSON data to a variable

For example, you can create a new JavaScript variable and assign the JSON formatted data string directly to it:

var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
] }

This is very simple; now people contains the JSON seen earlier format data. However, this isn't enough as the way to access the data doesn't seem obvious yet.

Access data

尽管看起来不明显,但是上面的长字符串实际上只是一个数组;将这个数组放进 JavaScript 变量之后,就可以很轻松地访问它。实际上,只需用点号表示法来表示数组元素。所以,要想访问 programmers 列表的第一个条目的姓氏,只需在 JavaScript 中使用下面这样的代码:

people.programmers[0].lastName;

注意,数组索引是从零开始的。所以,这行代码首先访问 people变量中的数据;然后移动到称为 programmers的条目,再移动到第一个记录([0]);最后,访问 lastName键的值。结果是字符串值 “McLaughlin”。

下面是使用同一变量的几个示例。

people.authors[1].genre // Value is "fantasy"
people.musicians[3].lastName // Undefined. This refers to the fourth entry, and there isn't one
people.programmers[2].firstName // Value is "Elliotte"

利用这样的语法,可以处理任何 JSON 格式的数据,而不需要使用任何额外的 JavaScript 工具包或 API。

 

修改 JSON 数据

正如可以用点号和括号访问数据,也可以按照同样的方式轻松地修改数据:

people.musicians[1].lastName = "Rachmaninov";

在将字符串转换为 JavaScript 对象之后,就可以像这样修改变量中的数据。

 

转换回字符串

当然,如果不能轻松地将对象转换回本文提到的文本格式,那么所有数据修改都没有太大的价值。在 JavaScript 中这种转换也很简单:

String newJSONtext = people.toJSONString();

这样就行了!现在就获得了一个可以在任何地方使用的文本字符串,例如,可以将它用作 Ajax 应用程序中的请求字符串。

更重要的是,可以将任何JavaScript 对象转换为 JSON 文本。并非只能处理原来用 JSON 字符串赋值的变量。为了对名为 myObject的对象进行转换,只需执行相同形式的命令:

String myObjectInJSON = myObject.toJSONString();

这就是 JSON 与本系列讨论的其他数据格式之间最大的差异。如果使用 JSON,只需调用一个简单的函数,就可以获得经过格式化的数据,可以直接使用了。对于其他数据格式,需要在原始数据和格式化数据之间进行转换。即使使用 Document Object Model 这样的 API(提供了将自己的数据结构转换为文本的函数),也需要学习这个 API 并使用 API 的对象,而不是使用原生的 JavaScript 对象和语法。

最终结论是,如果要处理大量 JavaScript 对象,那么 JSON 几乎肯定是一个好选择,这样就可以轻松地将数据转换为可以在请求中发送给服务器端程序的格式。

 

概念比较

JSON和XML的比较

◆可读性

JSON和XML的可读性可谓不相上下,一边是简易的语法,一边是规范的标签形式,很难分出胜负。

◆可扩展性

XML天生有很好的扩展性,JSON当然也有,没有什么是XML能扩展,而JSON却不能。不过JSON在Javascript主场作战,可以存储Javascript复合对象,有着xml不可比拟的优势。

◆编码难度

XML有丰富的编码工具,比如Dom4j、JDom等,JSON也有提供的工具。无工具的情况下,相信熟练的开发人员一样能很快的写出想要的xml文档和JSON字符串,不过,xml文档要多很多结构上的字符。

◆解码难度

XML的解析方式有两种:

一是通过文档模型解析,也就是通过父标签索引出一组标记。例如:xmlData.getElementsByTagName("tagName"),但是这样是要在预先知道文档结构的情况下使用,无法进行通用的封装。

另外一种方法是遍历节点(document 以及 childNodes)。这个可以通过递归来实现,不过解析出来的数据仍旧是形式各异,往往也不能满足预先的要求。

凡是这样可扩展的结构数据解析起来一定都很困难。

JSON也同样如此。如果预先知道JSON结构的情况下,使用JSON进行数据传递简直是太美妙了,可以写出很实用美观可读性强的代码。如果你是纯粹的前台开发人员,一定会非常喜欢JSON。但是如果你是一个应用开发人员,就不是那么喜欢了,毕竟xml才是真正的结构化标记语言,用于进行数据传递。

而如果不知道JSON的结构而去解析JSON的话,那简直是噩梦。费时费力不说,代码也会变得冗余拖沓,得到的结果也不尽人意。但是这样也不影响众多前台开发人员选择JSON。因为json.js中的toJSONString()就可以看到JSON的字符串结构。当然不是使用这个字符串,这样仍旧是噩梦。常用JSON的人看到这个字符串之后,就对JSON的结构很明了了,就更容易的操作JSON。

以上是在Javascript中仅对于数据传递的xml与JSON的解析。在Javascript地盘内,JSON毕竟是主场作战,其优势当然要远远优越于xml。如果JSON中存储Javascript复合对象,而且不知道其结构的话,我相信很多程序员也一样是哭着解析JSON的。

◆实例比较

XML和JSON都使用结构化方法来标记数据,下面来做一个简单的比较。

用XML表示中国部分省市数据如下:

<?xml version="1.0" encoding="utf-8"?>
<country>
    <name>中国</name>
    <province>
        <name>黑龙江</name>
     <cities>
            <city>哈尔滨</city>
            <city>大庆</city>
        </cities>
    </province>
    <province>
        <name>广东</name>
        <cities>
            <city>广州</city>
            <city>深圳</city>
            <city>珠海</city>
        </cities>
    </province>
</country>

用JSON表示如下:

{
{name:"中国", province:[ { name:"黑龙江", cities:{ city:["哈尔滨","大庆"] },
{name:"广东", cities:{ city:["广州","深圳","珠海"] } 
}

编码的可读性,xml有明显的优势,毕竟人类的语言更贴近这样的说明结构。json读起来更像一个数据块,读起来就比较费解了。不过,我们读起来费解的语言,恰恰是适合机器阅读,所以通过json的索引.province[0].name就能够读取“黑龙江”这个值。

编码的手写难度来说,xml还是舒服一些,好读当然就好写。不过写出来的字符JSON就明显少很多。去掉空白制表以及换行的话,JSON就是密密麻麻的有用数据,而xml却包含很多重复的标记字符。

 

JSON在线校验工具

前言

JSON格式取代了xml给网络传输带来了很大的便利,但是却没有了xml的一目了然,尤其是json数据很长的时候,我们会陷入繁琐复杂的数据节点查找中。

但是国人的一款在线工具 BeJson 给众多程序员带来了一阵凉风。

功能简介

1. JSON格式化校验

很多人在得到JSON数据后,一时没有办法判断JSON数据格式是否正确,是否少或多符号而导致程序不能解析,这个功能正好能帮助大家来完成JSON格式的校验。

2. JSON视图

想必很多程序员都会遇到当找一个节点的时候,会发现如果直接对着一行行数据无从下手,就算知道哪个位置,还要一个节点一个节点的往下找,万一一不留神又得从头开始找的麻烦事。

有了这个功能,一切JSON数据都会变成视图格式,一目了然,什么对象下有多少数组,一个数组下有多少对象。

这个功能非常实用。不光有视图功能还有格式化、压缩、转义、校验功能。总之很强大。

3. 压缩转义

程序员在写JSON语句测试用例的时候,很多时候为了方便直接写了个JSON字符串做测试,但是又陷入了无止境的双引号转义的麻烦中。这款功能集压缩、转义于一身,让你在写测试用例的时候,如鱼得水。

4. JSON在线编辑器

如果你现在的电脑刚巧没有装你所熟悉的编辑器,如果你想针对拿到的JSON数据的某个节点做数据修改时,这个功能可以满足你的需求。

5. 在线发送JSON数据

大家都知道,JSON用的最多的还是web项目的开发,那你要测试一个接口是否能准确的接受JSON数据,那你就得写一个页面发送JSON字符串,重复的做着这件事。随着这个功能的横空出世,你可以摆脱写测试页面了,因为这个功能可以将指定的JSON数据发送指定的url,方便吧。

6. JSON着色

很多人在写文档时,总希望文档能一目了然,但是面对着白底黑字的JSON数据总是提不起精神没关系,使用这个功能,所有的关键字都会被着色,数据结构一目了然。

7. JSON-XML互转

顾名思义,将JSON格式的数据转化成XML格式、或者XML格式的数据转化成JSON格式,一切都不是问题。


更多JSON 数据格式相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn