Home > Article > Web Front-end > js method analysis to convert json string to json object
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!