I believe that the front-end students are not unfamiliar with JSON, a lot of contact. But very few people know the full name of JSON, haha, I also check the information know. (JSON JavaScript Object notation is a lightweight data interchange format that is ideal for data interchange formats in a completely language-independent text format.) )
JSON can be passed as an array, or it can be passed as an object, my previous article PHP for the release version of the timeline data processing, the returned JSON format is an array json, and then contains objects, which is the JSON common format. Later, after the processing of PHP, the structure has changed, the outermost is an object, the inside is an array and objects.
In the data transfer process, JSON is passed in the form of text, which is a string, and JS operates on a JSON object, so the conversion between the JSON object and the JSON string is key. For example:
JSON string:
var str1 = ‘{ "name": "haorooms", "sex": "man" }‘;
JSON object:
var str2 = { "name": "haorooms", "sex": "man" };
One, JSON string converted to JSON object
To use the above str1, you must use the following to turn the lead into a JSON object (this is often encountered when the Ajax returns!). ):
//由JSON字符串转换为JSON对象var obj = eval(‘(‘ + str + ‘)‘);
Or
var obj = str.parseJSON(); //由JSON字符串转换为JSON对象
Or
var obj = JSON.parse(str); //由JSON字符串转换为JSON对象
Then, you can read this:
Alert(obj.name);Alert(obj.sex);
Special Note: If obj is originally a JSON object, then the use of the Eval () function after conversion (even if multiple conversions) is a JSON object, but the use of the Parsejson () function will be problematic (throwing a syntax exception).
Second, you can use toJSONString () or Global Essentials json.stringify () to convert the JSON object into a JSON string.
For example:
var last=obj.toJSONString(); //将JSON对象转化为JSON字符
Or
var last=JSON.stringify(obj); //将JSON对象转化为JSON字符alert(last);
In the above multiple essentials, in addition to the eval () function is JS comes from, the other main points are from the Json.js package. The new version of JSON modifies the API to inject json.stringify () and Json.parse () Two essentials into the Javascript built-in object, which becomes the object.tojsonstring (), and the latter becomes the Strin G.parsejson (). If you are prompted not to find the tojsonstring () and Parsejson () Essentials, your JSON package version is too low.
The above is a simple summary of JavaScript, some of which summarize the reference network. But many in peacetime to use, especially the JSON character to the operation of the object ! This is very important!
JavaScript, JS operation JSON method Summary (JSON character create transform JSON object)