Home > Web Front-end > JS Tutorial > body text

js method analysis to convert json string to json object

高洛峰
Release: 2017-01-18 09:58:16
Original
1215 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 str1 above, you must use The following method is first converted into a JSON object:

//Convert from 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 conversion using the eval() function (even if it is converted multiple times), but there will be problems after using the parseJSON() function to process it ( throws 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 into JSON characters

or

var last=JSON. stringify(obj); //Convert JSON objects into JSON characters

alert(last);

Note:

Among the above methods, except eval() In addition to the functions that come with js, several other methods 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.

For more js method analysis related articles on converting json strings into json objects, please pay attention to 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