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.