JS operation JSON summary in detail

  • 2020-03-30 02:12:03
  • OfStack

In JS, the JSON string is parsed into JSON data format in two ways:

1. One is to use the eval_r() function.

2. Use the Function object for return parsing.

In the data transfer process, json is passed in the form of text, that is, string, while JS operates on json objects, so the conversion between json objects and json strings is the key. Such as:

JSON string:
Var str1 = '{"name": "CXH ", "sex": "man"}';

JSON objects:
Var str2 = {"name": "CXH ", "sex": "man"};

The first solution:
Var dataObj = eval_r (" (" + data + ") "); // converted to json objects
"(" ("+data+")"); / / "?

Here's why: eval itself is a problem. Since json starts and ends with "{}," it is treated as a block of statements in JS, so it must be forced into an expression.

The purpose of the parentheses is to force the eval function to work with JavaScript code by forcing the expression inside the parentheses to be executed as an object, rather than as a statement. For example, if the object literal {} is not enclosed, then eval recognizes the braces as the start and end of JavaScript blocks, and {} is considered an empty statement. So the following two execution results are different:
Alert (eval_r (" {} "); / / return undefined
Alert (eval_r (" ({}) "); / / return the object [object]

For this type of writing, in JS, you can see it all over the place.

Such as: (function () {} ();   Wait while doing closure operations.

Var str1 = '{"name": "CXH ", "sex": "man"}';
Var data = eval_r (" (" + str1 + ") "); // convert to json object //data =(new
Alert (data. Name); // displays CXH

It is important to note that the eval_r() method in approach 1 executes the string (possibly a js script) dynamically, which can easily cause security problems for the system. Therefore, third-party client-side scripting libraries that circumvent eval_r() can be used, such as JSON in JavaScript, which provides a script library of up to 3k.

The second solution:
The second way of parsing is to use the Function object, which is typically used to parse return data such as success under AJAX methods in JQUERY
Var str1 = '{"name": "CXH ", "sex": "man"}';
Var data = (Function("","return "+str1))();
Alert (data. Name); // displays CXH


Related articles: