In the process of data transfer, JSON is passed in the form of text, which is a string, and JS is the JSON object, so the conversion between JSON object and JSON string is the key. For example:
JSON string:
var str1 = ' {' name ': ' cxh ', ' sex ': ' Man '} ';
JSON object:
var str2 = {"Name": "Cxh", "Sex": "Man"};
One, JSON string converted to JSON object
To use the above str1, you must first convert to a JSON object using the following method:
The JSON string is converted to a JSON object, and for an object declaration statement, it is executed only and cannot return a value. To return an object declaration statement such as a commonly used "{}", you must enclose it in parentheses to convert it to an expression in order to return its value
var obj = eval (' (' + str + ') ');
Or
var obj = Str.parsejson (); Convert from JSON string to JSON object
Or
var obj = json.parse (str); Convert from JSON string to JSON object
Then, you can read this:
Alert (Obj.name);
Alert (Obj.sex);
Special Note: If obj is originally a JSON object, then using the eval () function after conversion (even if multiple conversions) is a JSON object, but there is a problem with the Parsejson () function (throwing a syntax exception).
Second, the JSON object can be converted to a JSON string using tojsonstring () or global Method Json.stringify ().
For example:
var last=obj.tojsonstring (); Convert a JSON object to a JSON character
Or
var last=json.stringify (obj); Convert a JSON object to a JSON character
alert (last);
Attention:
In the above several methods, in addition to the eval () function is JS own, the other several methods are from the Json.js package. The new version of JSON modifies the API to inject json.stringify () and Json.parse () two methods 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 () methods, your JSON package version is too low.
Add a json2.js reference to the page.
Https://github.com/douglascrockford/JSON-js
Serialization methods
var = {id: ' jsonobj ', Name: ' Tom '}; Json.stringify (Jsonobj);
Deserialization method
var = "{id: ' jsonstring ', Name: ' Tom '}"; Json.parse (jsonstring);
JS converts the JSON string to JSON redemption