This article mainly introduces how to convert JSON strings and JSON objects, and analyzes in detail the conversion methods between json objects and JSON objects in the form of examples. We will share this with you for your reference. The details are as follows:
Converts a json string to a json object. During data transmission, json is transmitted in the form of text, that is, strings, while JS operates on JSON objects. Therefore, mutual conversion between JSON objects and JSON strings is critical.
For example:
JSON string:
var str = '{ "name": "name1","sex": "m" }';
JSON object:
var obj = { "name": "name1", "sex": "w" };
1. convert a JSON string to a JSON object
To use str1 above, you must use the following method to first convert it to a JSON object:
Var obj = eval ('+ str +'); // converts a JSON string to a JSON object. The text must be enclosed in brackets to avoid syntax errors: "(" + str + ")
Or
Var obj = $. parseJSON (str); // convert a JSON string to a JSON object (jQuery)
Or
Var obj = str. parseJSON (); // converts a JSON string to a JSON object.
Or
Var obj = JSON. parse (str); // converts a JSON string to a JSON object.
Then, you can read:
Alert(obj.name);Alert(obj.sex);
NOTE: If obj is a JSON object, it is still a JSON object after eval () function conversion (even Multiple conversions), but parseJSON () is used () A problem occurs after the function is processed (a syntax exception is thrown ).
2. You can use toJSONString () or the global method JSON. stringify () to convert a JSON object to a JSON string.
For example:
Var str = obj. toJSONString (); // convert a JSON object to a JSON character
Or
Var str = JSON. stringify (obj); // converts a JSON object to a JSON character alert (str );
Summary:
We have also seen two types of conversions in general. One is the built-in parser of JavaScript, and the other is the JSON parser, the javascript parser can compile and execute any javascript code, so a potential security problem is hidden here. The JSON parser can only recognize JSON text, rather than compile scripts, so it is safer, in addition, the JSON parser is faster.
Among the methods above, except that the eval () function is provided by js, several other methods are from the json. js package. The new JSON version modifies the API and changes JSON. stringify () and JSON. both parse () methods are injected into the built-in Javascript Object, and the former becomes the Object. toJSONString (), and the latter is a String. parseJSON (). If you cannot find the toJSONString () and parseJSON () methods, the version of your json package is too low.
I hope this article will help you design JavaScript programs.
For more details about examples of mutual conversion between JSON strings and JSON objects, please refer to the Chinese PHP website!