Home > Web Front-end > JS Tutorial > js method analysis to convert json string to json object_javascript skills

js method analysis to convert json string to json object_javascript skills

WBOY
Release: 2016-05-16 17:15:57
Original
1246 people have browsed it

For example:

JSON string:
var str1 = '{ "name": "cxh", "sex": "man" }';
JSON object:
var str2 = { "name": "cxh", "sex": "man" };

1. Convert JSON string to JSON object

To use the str1 above, you must first convert it into a JSON object using the following method:

//Convert JSON string to JSON object

var obj = eval('(' str ')');

or

var obj = str.parseJSON(); //Convert JSON string to JSON object

or

var obj = JSON.parse(str); //Convert JSON string to JSON object

Then, you can read it like this:

Alert(obj.name);

Alert(obj.sex);

Special note: If obj is originally a JSON object, then it will still be a JSON object after using the eval() function to convert it (even if it is converted multiple times), but there will be problems after using the parseJSON() function to process it (throwing a syntax exception) .

2. You can use toJSONString() or the global method JSON.stringify() to convert the JSON object into a JSON string.

For example:

var last=obj.toJSONString(); //Convert JSON object to JSON character

or

var last=JSON.stringify(obj); //Convert JSON object to JSON character

alert(last);

Note:

Among the above methods, except for the eval() function, which comes with js, the other methods all come from the json.js package. The new version of JSON modifies the API and injects both JSON.stringify() and JSON.parse() methods into the built-in objects of Javascript. The former becomes Object.toJSONString(), and the latter becomes String. parseJSON(). If you are prompted that the toJSONString() and parseJSON() methods cannot be found, it means that your json package version is too low.

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