Home > Web Front-end > JS Tutorial > Deep understanding of JSON

Deep understanding of JSON

巴扎黑
Release: 2017-04-29 14:41:47
Original
1014 people have browsed it

Let’s first look at a common problem in JS about serializing JS objects into JSON strings. What does the following JS object’s string look like after passing JSON.stringify? Don't rush to copy and paste it into the console. First open a code editor or paper, write and read, and then carefully compare your console output after writing. If you make any mistakes, remember to read the entire text and comment, haha.

var friend={  
    firstName: 'Good',
    'lastName': 'Man',
    'address': undefined,
    'phone': ["1234567",undefined],
    'fullName': function(){
        return this.firstName + ' ' + this.lastName;
    }
};

JSON.stringify(friend);//这一行返回什么呢?
Copy after login

Second question, if I want to change the 'friend''s name into all uppercase letters in the final JSON string, that is, change "Good" into "GOOD" and "Man" into "MAN", then I can How to do it?

Based on the above two questions, let’s go back to the source and ask, what exactly is JSON? Why is JSON easy to exchange data? What is the difference between JSON and JS objects? In JS, JSON.parse, JSON.stringify and the uncommon toJSON, what are the parameters and processing details of these functions?

Welcome to this "JSON Digging Journey", below we will understand JSON from the following aspects:

  • The first is the understanding of "JSON is a lightweight data exchange format";


  • Then look at the difference between JSON and JS objects that are often confused;


  • Finally, let’s look at the specific execution details of these JSON-related functions in JS.

I hope that the full text will help those who know little about JSON like me before to be able to explain clearly what JSON is, and be able to use JSON proficiently, and know what the output is after JS objects are serialized into JSON strings without looking at the console.

1. JSON is a format, based on text, more lightweight, used to exchange data

If you have not been to the official introduction of JSON, you can go here. The first and second paragraphs of the official introduction have clearly stated what JSON is. I have refined what JSON is into the following aspects:

1. A data format

What is format? It is to standardize how your data should be expressed. For example, there is a person named "Two Hundred Six", with a height of "160cm" and a weight of "60kg". Now you want to pass this person's information to others or something else. You have many choices:

  • Name "260", height "160cm", weight "60kg"


  • name="two hundred six"&height="160cm"&weight="60kg"


  • two hundred six16060


  • {"name":"二百六","height":160,"weight":60}


  • ... ...

For all the above choices, the data transferred is the same, but you can see that the forms can be various. This is the data in various formats, and JSON is one of the representation methods.

2. Text-based data format

JSON is a text-based data format, as opposed to binary-based data, so when JSON is passed, it passes a string that conforms to the format of JSON (as for what the format of JSON is, we will talk about it in the second part), we often call it " JSON string".

3. Lightweight data format

Before JSON, there was a data format called xml, which is still widely used today, but JSON is more lightweight. For example, xml requires a lot of tags. In the example above, you can clearly see that the tags themselves occupy the xml format data. It takes up a lot of space, and JSON is relatively lightweight, that is, the same data takes up less bandwidth in JSON format, which has obvious advantages when a large amount of data is requested and transmitted.

4. Widely used for data exchange

Lightweight is already an advantage for data exchange, but more importantly, JSON is easy to read, write and machine parse, that is, this JSON is friendly to both humans and machines, and is light and language independent (because it is text-based), so JSON is widely used for data exchange.

Take the front-end JS to make an ajax POST request as an example, and the back-end PHP to process the request as an example:

  1. The front end constructs a JS object to wrap the data to be transmitted, then converts the JS object into a JSON string, and then sends the request to the back end;


  2. The backend PHP receives this JSON string, converts the JSON string into a PHP object, and then processes the request.

As you can see, the same data has three different forms of expression here, namely the front-end JS object, the transmitted JSON string, and the back-end PHP object. JS objects and PHP objects are obviously not the same thing, but because everyone uses JSON is used to transmit data. Everyone can understand this data format and can easily convert the JSON data format into a data structure they can understand. This is convenient for exchanging data in various other language environments. This is true.

2. "Gossip" between JSON and JS objects

I often hear the phrase "JSON is a subset of JS", and I have always thought so. Every string that conforms to the JSON format can be parsed into js, ​​until I discovered it later. A strange thing...

1. Why are two essentially different things so closely connected

JSON and JS objects are essentially the same thing, just like "zebra crossing" and "zebra". "Zebra crossing" is presented and named based on the stripes on the "zebra", but zebras are alive and zebra crossings are non-living things.

Similarly, the full name of "JSON" is "JavaScript Object Notation", so its format (syntax) is based on JS, but it is a format, and the JS object is an instance, a thing that exists in memory.

Just kidding, if JSON is based on PHP, it may be called PON, and the form may be like this ['propertyOne' => 'foo', 'propertyTwo' => 42,]. If so, then JSON Maybe it is more closely related to PHP now.

In addition, JSON can be transmitted because it is in text format, but JS objects cannot be transmitted. In terms of syntax, JSON will be more strict, but JS objects are very loose.

So why are two different things so close? Because after all, JSON evolved from JS and has similar syntax.

2. What is the strict syntax of JSON format compared to JS object

Let’s first compare the differences between the two in the form of “objects expressed as key-value pairs”. As for how JSON can be expressed in other forms, we will list them after the comparison.

Compare content JSON JS Object

Key name

Must be enclosed in double quotes

Allowed without, with single quotes, or with double quotes

Attribute value

It can only be numerical values ​​(decimal), strings (double quotes), Boolean values ​​and null,
It can also be an array or an object that meets JSON requirements,
Cannot be a function, NaN, Infinity, -Infinity and undefined

What do you love

Comma problem

There cannot be a comma

after the last attribute

Can

Value

Leading 0 cannot be used, there must be digits after the decimal point

No restrictions

  可以看到,相对于JS对象,JSON的格式更严格,所以大部分写的JS对象是不符合JSON的格式的。

以下代码引用自这里

var obj1 = {}; // 这只是 JS 对象

// 可把这个称做:JSON 格式的 JavaScript 对象 
var obj2 = {"width":100,"height":200,"name":"rose"};

// 可把这个称做:JSON 格式的字符串
var str1 = '{"width":100,"height":200,"name":"rose"}';

// 这个可叫 JSON 格式的数组,是 JSON 的稍复杂一点的形式
var arr = [  
    {"width":100,"height":200,"name":"rose"},
    {"width":100,"height":200,"name":"rose"},
    {"width":100,"height":200,"name":"rose"},
];

// 这个可叫稍复杂一点的 JSON 格式的字符串     
var str2='['+  
    '{"width":100,"height":200,"name":"rose"},'+
    '{"width":100,"height":200,"name":"rose"},'+
    '{"width":100,"height":200,"name":"rose"},'+
']';
Copy after login

  另外,除了常见的“正常的”JSON格式,要么表现为一个对象形式{...},要么表现为一个数组形式[...],任何单独的一个10进制数值、双引号字符串、布尔值和null都是有效符合JSON格式的。

  这里有完整的JSON语法参考

  3. 一个有意思的地方,JSON不是JS的子集

  首先看下面的代码,你可以copy到控制台执行下:

var code = '"\u2028\u2029"';  
JSON.parse(code); // works fine  
eval(code); // fails
Copy after login

  这两个字符\u2028和\u2029分别表示行分隔符和段落分隔符,JSON.parse可以正常解析,但是当做js解析时会报错。

 三、这几个JS中的JSON函数,弄啥嘞

  在JS中我们主要会接触到两个和JSON相关的函数,分别用于JSON字符串和JS数据结构之间的转化,一个叫JSON.stringify,它很聪明,聪明到你写的不符合JSON格式的JS对象都能帮你处理成符合JSON格式的字符串,所以你得知道它到底干了什么,免得它只是自作聪明,然后让你Debug long time;另一个叫JSON.parse,用于转化json字符串到JS数据结构,它很严格,你的JSON字符串如果构造地不对,是没办法解析的。

  而它们的参数不止一个,虽然我们经常用的时候只传入一个参数。

  此外,还有一个toJSON函数,我们较少看到,但是它会影响JSON.stringify。

  1. 将JS数据结构转化为JSON字符串——JSON.stringify

  这个函数的函数签名是这样的:

JSON.stringify(value[, replacer [, space]])
Copy after login

  下面将分别展开带1~3个参数的用法,最后是它在序列化时做的一些“聪明”的事,要特别注意。

  1.1 基本使用——仅需一个参数

  这个大家都会使用,传入一个JSON格式的JS对象或者数组,JSON.stringify({"name":"Good Man","age":18})返回一个字符串"{"name":"Good Man","age":18}"。

  可以看到本身我们传入的这个JS对象就是符合JSON格式的,用的双引号,也没有JSON不接受的属性值,那么如果像开头那个例子中的一样,how to play?不急,我们先举简单的例子来说明这个函数的几个参数的意义,再来说这个问题。

  1.2 第二个参数可以是函数,也可以是一个数组

  • 如果第二个参数是一个函数,那么序列化过程中的每个属性都会被这个函数转化和处理


  • 如果第二个参数是一个数组,那么只有包含在这个数组中的属性才会被序列化到最终的JSON字符串中


  • 如果第二个参数是null,那作用上和空着没啥区别,但是不想设置第二个参数,只是想设置第三个参数的时候,就可以设置第二个参数为null

  这第二个参数若是函数

var friend={  
    "firstName": "Good",
    "lastName": "Man",
    "phone":"1234567",
    "age":18
};

var friendAfter=JSON.stringify(friend,function(key,value){  
    if(key==="phone")
        return "(000)"+value;
    else if(typeof value === "number")
        return value + 10;
    else
        return value; //如果你把这个else分句删除,那么结果会是undefined
});

console.log(friendAfter);  
//输出:{"firstName":"Good","lastName":"Man","phone":"(000)1234567","age":28}
Copy after login

  如果制定了第二个参数是函数,那么这个函数必须对每一项都有返回,这个函数接受两个参数,一个键名,一个是属性值,函数必须针对每一个原来的属性值都要有新属性值的返回。

  那么问题来了,如果传入的不是键值对的对象形式,而是方括号的数组形式呢?,比如上面的friend变成这样:friend=["Jack","Rose"],那么这个逐属性处理的函数接收到的key和value又是什么?如果是数组形式,那么key是索引,而value是这个数组项,你可以在控制台在这个函数内部打印出来这个key和value验证。

  这第二个参数若是数组

var friend={  
    "firstName": "Good",
    "lastName": "Man",
    "phone":"1234567",
    "age":18
};

//注意下面的数组有一个值并不是上面对象的任何一个属性名
var friendAfter=JSON.stringify(friend,["firstName","address","phone"]);

console.log(friendAfter);  
//{"firstName":"Good","phone":"1234567"}
//指定的“address”由于没有在原来的对象中找到而被忽略
Copy after login

  如果第二个参数是一个数组,那么只有在数组中出现的属性才会被序列化进结果字符串,只要在这个提供的数组中找不到的属性就不会被包含进去,而这个数组中存在但是源JS对象中不存在的属性会被忽略,不会报错。

  1.3 第三个参数用于美化输出——不建议用

  指定缩进用的空白字符,可以取以下几个值:

  • 是1-10的某个数字,代表用几个空白字符


  • 是字符串的话,就用该字符串代替空格,最多取这个字符串的前10个字符


  • 没有提供该参数 等于 设置成null 等于 设置一个小于1的数

var friend={  
    "firstName": "Good",
    "lastName": "Man",
    "phone":{"home":"1234567","work":"7654321"}
};

//直接转化是这样的:
//{"firstName":"Good","lastName":"Man","phone":{"home":"1234567","work":"7654321"}}

var friendAfter=JSON.stringify(friend,null,4);  
console.log(friendAfter);  
/*
{
    "firstName": "Good",
    "lastName": "Man",
    "phone": {
        "home": "1234567",
        "work": "7654321"
    }
}
*/

var friendAfter=JSON.stringify(friend,null,"HAHAHAHA");  
console.log(friendAfter);  
/*
{
HAHAHAHA"firstName": "Good",  
HAHAHAHA"lastName": "Man",  
HAHAHAHA"phone": {  
HAHAHAHAHAHAHAHA"home": "1234567",  
HAHAHAHAHAHAHAHA"work": "7654321"  
HAHAHAHA}  
}
*/

var friendAfter=JSON.stringify(friend,null,"WhatAreYouDoingNow");  
console.log(friendAfter);  
/* 最多只取10个字符
{
WhatAreYou"firstName": "Good",  
WhatAreYou"lastName": "Man",  
WhatAreYou"phone": {  
WhatAreYouWhatAreYou"home": "1234567",  
WhatAreYouWhatAreYou"work": "7654321"  
WhatAreYou}  
}
*/
Copy after login

  笑笑就好,别这样用,序列化是为了传输,传输就是能越小越好,加莫名其妙的缩进符,解析困难(如果是字符串的话),也弱化了轻量化这个特点。。

  1.4 注意这个函数的“小聪明”(重要)

  如果有其他不确定的情况,那么最好的办法就是"Have a try",控制台做下实验就明了。

  • 键名不是双引号的(包括没有引号或者是单引号),会自动变成双引号;字符串是单引号的,会自动变成双引号


  • 最后一个属性后面有逗号的,会被自动去掉


  • 非数组对象的属性不能保证以特定的顺序出现在序列化后的字符串中
    这个好理解,也就是对非数组对象在最终字符串中不保证属性顺序和原来一致


  • 布尔值、数字、字符串的包装对象在序列化过程中会自动转换成对应的原始值
    也就是你的什么new String("bala")会变成"bala",new Number(2017)会变成2017


  • undefined、任意的函数(其实有个函数会发生神奇的事,后面会说)以及 symbol 值(symbol详见ES6对symbol的介绍)

    • 出现在非数组对象的属性值中:在序列化过程中会被忽略


    • 出现在数组中时:被转换成 null


JSON.stringify({x: undefined, y: function(){return 1;}, z: Symbol("")});  
//出现在非数组对象的属性值中被忽略:"{}"
JSON.stringify([undefined, Object, Symbol("")]);  
//出现在数组对象的属性值中,变成null:"[null,null,null]"
Copy after login
  • NaN、Infinity和-Infinity,不论在数组还是非数组的对象中,都被转化为null


  • 所有以 symbol 为属性键的属性都会被完全忽略掉,即便 replacer 参数中强制指定包含了它们


  • 不可枚举的属性会被忽略

  2. 将JSON字符串解析为JS数据结构——JSON.parse

  这个函数的函数签名是这样的:

JSON.parse(text[, reviver])
Copy after login

  如果第一个参数,即JSON字符串不是合法的字符串的话,那么这个函数会抛出错误,所以如果你在写一个后端返回JSON字符串的脚本,最好调用语言本身的JSON字符串相关序列化函数,而如果是自己去拼接实现的序列化字符串,那么就尤其要注意序列化后的字符串是否是合法的,合法指这个JSON字符串完全符合JSON要求的严格格式。

  值得注意的是这里有一个可选的第二个参数,这个参数必须是一个函数,这个函数作用在属性已经被解析但是还没返回前,将属性处理后再返回。

var friend={  
    "firstName": "Good",
    "lastName": "Man",
    "phone":{"home":"1234567","work":["7654321","999000"]}
};

//我们先将其序列化
var friendAfter=JSON.stringify(friend);  
//'{"firstName":"Good","lastName":"Man","phone":{"home":"1234567","work":["7654321","999000"]}}'

//再将其解析出来,在第二个参数的函数中打印出key和value
JSON.parse(friendAfter,function(k,v){  
    console.log(k);
    console.log(v);
    console.log("----");
});
/*
firstName  
Good  
----
lastName  
Man  
----
home  
1234567  
----
0  
7654321  
----
1  
999000  
----
work  
[]
----
phone  
Object  
----

Object  
----
*/
Copy after login

  仔细看一下这些输出,可以发现这个遍历是由内而外的,可能由内而外这个词大家会误解,最里层是内部数组里的两个值啊,但是输出是从第一个属性开始的,怎么就是由内而外的呢?

  这个由内而外指的是对于复合属性来说的,通俗地讲,遍历的时候,从头到尾进行遍历,如果是简单属性值(数值、字符串、布尔值和null),那么直接遍历完成,如果是遇到属性值是对象或者数组形式的,那么暂停,先遍历这个子JSON,而遍历的原则也是一样的,等这个复合属性遍历完成,那么再完成对这个属性的遍历返回。

  本质上,这就是一个深度优先的遍历。

  有两点需要注意:

  • 如果 reviver 返回 undefined,则当前属性会从所属对象中删除,如果返回了其他值,则返回的值会成为当前属性新的属性值。


  • 你可以注意到上面例子最后一组输出看上去没有key,其实这个key是一个空字符串,而最后的object是最后解析完成对象,因为到了最上层,已经没有真正的属性了。

  3. 影响 JSON.stringify 的神奇函数——object.toJSON

  如果你在一个JS对象上实现了toJSON方法,那么调用JSON.stringify去序列化这个JS对象时,JSON.stringify会把这个对象的toJSON方法返回的值作为参数去进行序列化。

var info={  
    "msg":"I Love You",
    "toJSON":function(){
        var replaceMsg=new Object();
        replaceMsg["msg"]="Go Die";
        return replaceMsg;
    }
};

JSON.stringify(info);  
//出si了,返回的是:'"{"msg":"Go Die"}"',说好的忽略函数呢
Copy after login

  这个函数就是这样子的。

  其实Date类型可以直接传给JSON.stringify做参数,其中的道理就是,Date类型内置了toJSON方法。

4. Summary and issues about compatibility

At this point, I finally sorted out JSON and JSON in JS, and also went through the details and points of attention. I know that JSON is a lightweight data exchange format that is grammatically derived from the JS language. , and also understood the difference between JSON and general JS data structures (especially objects), and further discussed in detail the three functions and details of JSON processing in JS.

Unfortunately, the three functions used above are not compatible with IE7 and browsers before IE7. Discussion of compatibility will be left for later. If you want to solve the compatibility problem directly in the application, you can apply the official JSON js to solve the problem.

If there are any mistakes, please leave a message to point them out.

The above is the detailed content of Deep understanding of JSON. For more information, please follow other related articles on the PHP Chinese website!

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