Crazy XML study notes (4)------------XML's rival JSON

黄舟
Release: 2017-02-21 14:20:55
Original
1490 people have browsed it

JSON (JavaScript Object Notation) is a lightweight data exchange format.

It is based on a subset of JavaScript (Standard ECMA-262 3rd Edition - December 1999).

JSON uses a completely language-independent text format, but also uses conventions similar to the C language family (including C, C++, C#, Java, JavaScript, Perl, Python, etc.) .

These features make JSON an ideal data exchange language. Easy for humans to read and write, and easy for machines to parse and generate (network transmission speed).

JSON Syntax

JSON syntax rules

JSON syntax is a JavaScript object Represents a subset of the grammar.

  • Data is in name/value pairs

  • Data is separated by commas

  • Curly brackets save objects

  • ##Square brackets save arrays

JSON name/value pair

The writing format of JSON data is: name/value pair.

The name in the name/value pair combination is written first (in double quotes), and the value pair is written after (also in double quotes), separated by a colon:

"firstName":"John"
Copy after login

This is easy to understand and is equivalent to this JavaScript statement:

firstName="John"
Copy after login

JSON value can be: JSON value

  • ##Number

    (integer or float)

  • String (in double quotes)

  • Logical value (true or false)

  • Array (in square brackets)

  • Object (in curly braces)

  • null

2Basic structure

JSON

The structure has two structures

Json simply means objects and arrays in JavaScript, so these two structures are objects and arrays. Various complex structures can be expressed through these two structures

1. Object: The object is represented in js as the content enclosed by "{}", and the data structure is the key-value pair structure of {key: value, key: value,...}, in an object-oriented language , key is the attribute of the object, and value is the corresponding attribute value, so it is easy to understand. The value method is object.key to obtain the attribute value. The type of this attribute value can be numbers, strings, arrays, and objects.

2. Array: Array in js is the content enclosed by square brackets "[]", and the data structure is ["

java ","javascript","vb",...], the value method is the same as in all languages, using index to obtain, the type of field value can be Numbers, strings, arrays, objects.

Complex data structures can be combined through the two structures of objects and arrays.

3基础示例

简单地说,JSON 可以将 JavaScript 对象中表示的一组数据转换为字符串,然后就可以在函数之间轻松地传递这个字符串,或者在异步应用程序中将字符串从 Web 客户机传递给服务器端程序。这个字符串看起来有点儿古怪,但是JavaScript很容易解释它,而且 JSON 可以表示比"名称 / 值对"更复杂的结构。例如,可以表示数组和复杂的对象,而不仅仅是键和值的简单列表。

名称 / 值对

按照最简单的形式,可以用下面这样的 JSON 表示"名称 / 值对":

"firstName":"Brett"}
Copy after login

这个示例非常基本,而且实际上比等效的纯文本"名称 / 值对"占用更多的空间:

firstName=Brett
Copy after login


但是,当将多个"名称 / 值对"串在一起时,JSON 就会体现出它的价值了。首先,可以创建包含多个"名称 / 值对"的 记录,比如:

{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}
Copy after login


表示数组从语法方面来看,这与"名称 / 值对"相比并没有很大的优势,但是在这种情况下 JSON 更容易使用,而且可读性更好。例如,它明确地表示以上三个值都是同一记录的一部分;花括号使这些值有了某种联系。

当需要表示一组值时,JSON 不但能够提高可读性,而且可以减少复杂性。例如,假设您希望表示一个人名列表。在XML中,需要许多开始标记和结束标记;如果使用典型的名称 / 值对(就像在本系列前面文章中看到的那种名称 / 值对),那么必须建立一种专有的数据格式,或者将键名称修改为 person1-firstName这样的形式。

如果使用 JSON,就只需将多个带花括号的记录分组在一起:

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


这不难理解。在这个示例中,只有一个名为 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":"sciencefiction"},
{"firstName":"Tad","lastName":"Williams","genre":"fantasy"},
{"firstName":"Frank","lastName":"Peretti","genre":"christianfiction"}
],
"musicians":[
{"firstName":"Eric","lastName":"Clapton","instrument":"guitar"},
{"firstName":"Sergei","lastName":"Rachmaninoff","instrument":"piano"}
]}
Copy after login


在处理 JSON 格式的数据时,没有需要遵守的预定义的约束。所以,在同样的数据结构中,可以改变表示数据的方式,甚至可以以不同方式表示同一事物。
这里最值得注意的是,能够表示多个值,每个值进而包含多个值。但是还应该注意,在不同的主条目(programmers、authors 和 musicians)之间,记录中实际的名称 / 值对可以不一样。JSON 是完全动态的,允许在 JSON 结构的中间改变表示数据的方式。

4格式应用

掌握了 JSON 格式之后,在 JavaScript 中使用它就很简单了。JSON 是 JavaScript 原生格式,这意味着在 JavaScript 中处理 JSON 数据不需要任何特殊的 API 或工具包。

赋值给变量

例如,可以创建一个新的 JavaScript 变量,然后将 JSON 格式的数据字符串直接赋值给它:

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":"sciencefiction"},
{"firstName":"Tad","lastName":"Williams","genre":"fantasy"},
{"firstName":"Frank","lastName":"Peretti","genre":"christianfiction"}
],
"musicians":[
{"firstName":"Eric","lastName":"Clapton","instrument":"guitar"},
{"firstName":"Sergei","lastName":"Rachmaninoff","instrument":"piano"}
]}
Copy after login



这非常简单;people包含前面看到的 JSON 格式的数据。但是,这还不够,因为访问数据的方式似乎还不明显。

访问数据

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

people.programmers[0].lastName;
Copy after login


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


people.authors[1].genre//Valueis"fantasy"
people.musicians[3].lastName//Undefined.Thisreferstothefourthentry,andthereisn'tone
people.programmers[2].firstName//Valueis"Elliotte"
Copy after login


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

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

?

people.musicians[1].lastName="Rachmaninov";
Copy after login


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

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

5具体形式

1、对象是一个无序的“‘名称/值’对”集合。[3]

(1)一个对象以“{”(左括号)开始,“}”(右括号)结束。

(2)每个“名称”后跟一个“:”(冒号);

(3)“‘名称/值’ 对”之间使用“,”(逗号)分隔。(如图所示,图中表示数据的方式是类似非确定性自动机的形式,没学过编译原理的人,可能理解起来困难点,实际上也是正则表达式的形式。下同)


例子:表示人的一个对象:

{
"姓名":"大憨",
"年龄":24
}
Copy after login


(1)一个数组以“[”(左中括号)开始,“]”(右中括号)结束。
2、数组是值(value)的有序集合。

(2)值之间使用“,”(逗号)分隔。

例子:一组学生

{
"学生":
[
{"姓名":"小明","年龄":23},
{"姓名":"大憨","年龄":24}
]
}
Copy after login


说明:此Json对象包括了一个学生数组,而学生数组中的值又是两个Json对象。


3. Value (value) can be characters enclosed in double quotes String, number, true, false, null, object or array. These structures can be nested.



##4, CharactersString (string) is a collection of any number of Unicode characters surrounded by double quotes. Use backslash to convert righteous. A character (character) is a single string (character string). Strings are very similar to C or Java strings.



##5. The numerical value (number) is also very similar to the numerical value of C or

Java. Remove the unused octal and hexadecimal formats. Removed some encoding details.


##6

Concept Comparison

##Comparison with XMLReadability

JSON and

The readability of XML

can be said to be comparable. One side has simple syntax, and the other side has standardized tag format. It is difficult to distinguish the winner. Scalability

XML

is naturally very scalable, of course JSON also has it, nothing is XML Can be extended but JSON cannot be extended. However, JSON is at home in Javascript and can store Javascript composite objects, which has incomparable advantages over xml.

Coding difficulty

XML

There are rich

coding tools , such as Dom4j, JDom, etc., JSON also provides tools. Without tools, I believe that skilled developers can quickly write the desired xml document and JSON character string. However, the xml document requires a lot more structure. character. Decoding difficulty

There are two ways to parse XML

:

The first is to parse through the document model, that is, to index a set of tags through the parent tag. For example: xmlData.getElementsByTagName("tagName"), but this must be used when the document structure is known in advance and cannot be universally encapsulated.

Another method is to traverse the nodes (document and childNodes). This can be achieved through

recursion

, but the parsed data is still in different forms and often cannot meet the pre-existing requirements. It must be very difficult to parse such scalable structured data.

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

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

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

除了上述之外,JSON和XML还有另外一个很大的区别在于有效数据率。JSON作为数据包格式传输的时候具有更高的效率,这是因为JSON不像XML那样需要有严格的闭合标签,这就让有效数据量与总数据包比大大提升,从而减少同等数据流量的情况下,网络的传输压力[4]

实例比较

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

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

<?xmlversion="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>
    <province>
        <name>台湾</name>
        <cities>
            <city>台北</city>
            <city>高雄</city>
        </cities>
    </province>
    <province>
        <name>新疆</name>
        <cities>
            <city>乌鲁木齐</city>
        </cities>
    </province>
</country>
Copy after login

用JSON表示如下:

{
"name":"中国",
"province":[{"name":"黑龙江","cities":{"city":["哈尔滨","大庆"]}},
            {"name":"广东","cities":{"city":["广州","深圳","珠海"]}},
            {"name":"台湾","cities":{"city":["台北","高雄"]}},
            {"name":"新疆","cities":{"city":["乌鲁木齐"]}}
           ]
}
Copy after login



编码的手写难度来说,xml还是舒服一些,好读当然就好写。不过写出来的
字符JSON就明显少很多。去掉空白制表以及换行的话,JSON就是密密麻麻的有用数据,而xml却包含很多重复的标记字符编码的可读性,xml有明显的优势,毕竟人类的语言更贴近这样的说明结构。json读起来更像一个数据块,读起来就比较费解了。不过,我们读起来费解的语言,恰恰是适合机器阅读,所以通过json的索引.province[0].name就能够读取“黑龙江”这个值。

 

7校验工具

前言

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

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

功能

1 JSON格式化校验

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

2 JSON视图

I think many programmers will encounter the problem that when looking for a node, they will find that if they directly look at the rows of data, they have no way to start. Even if they know the location, they have to search node by node, just in case. If you are not careful, you will have to start from scratch again.

With this function, all JSON data will be converted into a view format, and it will be clear at a glance how many arraysare under which object, under one array How many objects are there.

This function is very practical. It not only has view functions but also formatting, compression, escaping, and verification functions. All in all very powerful.

3 Compression escape

Programmer writing JSON statementTest case, many times I directly write a JSON string for testing for convenience, but I get into the endless trouble of escaping double quotes. This function combines compression and escaping, allowing you to write test cases like a duck in water.

4 JSON Online Editor

If your current computer happens to not have an editor you are familiar with installed, If you want to make data modification to a certain node of the JSON data you obtained, this function can meet your needs.

5 Send JSON data online

As we all know, JSON is most commonly used in the development of web projects. Then if you want to test whether an interface can accurately accept JSON data, then you have to write a page to send a JSON string and do this repeatedly. With the advent of this function, you can get rid of writing test pages, because this function can send the specified JSON data to the specified URL, which is convenient.

6 JSON coloring

When many people write documents, they always hope that the document can be clear at a glance, but when faced with It doesn’t matter if the JSON data with black text on a white background is always boring. Using this function, all keywords will be colored, and the data will be colored. The structure is clear at a glance. 7 JSON-XML conversion

As the name suggests, convert JSON format data into XML[ 1]

format, or XML format data is converted into JSON format, nothing is a problem. 8 JSON-VIEW

JSON viewing utility tool, you can view it during the development process (in windows platform) JSON data is formatted and displayed in a view.

9 It is a data exchange format like xml

The above is the content of Crazy XML Study Notes (4)------------XML's rival JSON. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com )!

##

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!