Home >Web Front-end >JS Tutorial >Detailed summary of JS operation JSON_javascript skills
There are generally two ways to parse JSON strings into JSON data format in JS:
1. One is to use the eval_r() function.
2. Use Function object to perform return analysis.
In the data transmission process, json is transmitted in the form of text, that is, a string, and JS operates on JSON objects, so the conversion between JSON objects and JSON strings is the key. For example:
JSON string:
var str1 = '{ "name": "cxh", "sex": "man" }';
JSON object:
var str2 = { "name": "cxh", "sex": "man" };
The first solution:
var dataObj=eval_r("(" data ")");//Convert to json object
Why eval What about adding "("(" data ")");//" here?
The reason is: the problem of eval itself. Since json starts and ends with "{}", it will be processed as a statement block in JS, so it must be forced to be converted into an expression.
The purpose of adding parentheses is to force the eval function to convert the expression in the parentheses into an object instead of executing it as a statement when processing JavaScript code. For example, take the object literal {}. If no outer brackets are added, then eval will recognize the braces as the beginning and end marks of the JavaScript code block, and {} will be considered to execute an empty statement. So the following two execution results are different:
alert(eval_r("{}"); // return undefined
alert(eval_r("({})"); // return object[Object]
This kind of writing can be seen everywhere in JS.
For example: (function()) {}(); When doing closure operations, etc.
var str1 = '{ "name": "cxh", "sex": "man" }';
var data=eval_r("(" str1 ")");//Convert to json object/ /data =(new
alert (data.name);//cxh
What needs special attention here is that the eval_r() method in method 1 dynamically executes the string (possibly a js script), which can easily cause system security issues. Therefore, you can use some third-party client script libraries that circumvent eval_r(). For example, JSON in JavaScript provides a script library of no more than 3k.
The second solution:
The second parsing method is to use the Function object. Its typical application is success under the AJAX method in JQUERY. Wait for the analysis of the returned data data
var str1 = '{ "name": "cxh", "sex": "man" }';
var data = (Function("","return " str1) )();
alert (data.name);//cxh