The best way to convert a JSON string into a JSON object in js

  • 2020-03-30 02:24:39
  • OfStack

In JS, the JSON string is parsed into JSON data format in two ways:
One is to use the eval() function.
2. Use the Function object for return parsing.
 
The first way to do this is to use the eval function for parsing and to use jQuery's each method for traversal
The method of parsing JSON data with jQuery is used as the transmission object of jQuery asynchronous request. The result returned by jQuery after the request is JSON object. Here, we consider the form of string returned by the server in JSON form.
The JSON string set is first shown here, and the string set is as follows:

var data = " {
root:
    [
        {name: '1', value: '0'},
        {name: '6101', value: ' The Beijing municipal '},
        {name: '6102', value: ' tianjin '},
        {name: '6103', value: ' Shanghai '},
        {name: '6104', value: ' chongqing '},
        {name: '6105', value: ' weinan '},
        {name: '6106', value: ' Yan 'an '},
        {name: '6107', value: ' Grassland, '},
        {name: '6108', value: ' Yulin city '},
        {name: '6109', value: ' Ankang municipality '},
        {name: '6110', value: ' shangluo '}
    ]
}
";

Based on the data types obtained asynchronously by jQuery -- json objects and strings, this paper introduces the result processing methods obtained in two ways.
1. If the JSON string returned by the server is not typed or accepted as a string by the jQuery asynchronous request, then it needs to be objectized once, either by placing the string in eval() and executing it once. This method is also suitable for the common javascript method to obtain json objects, the following examples:
var dataObj = eval("(" + data + ")");  //  convert json object 

 
"(" (" + data + ")");" ?
Here's why: eval itself is a problem. Since json starts and ends with a '{}', in JS it is treated as a block of statements, 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("{}"); // return undefined
alert(eval("({})");// return 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.
alert(dataObj.root.length);//The number of child objects of the output root 
$.each(dataObj.root, fucntion(idx, item) {
 if (idx == 0) {
  return true;
 }  //Output the name and value of each root child object
 alert("name:" + item.name + ",value:" + item.value);
})

 
2, for the server returns a JSON string, if the jQuery asynchronous request will type (generally) for this configuration attribute set to "JSON", or use $. GetJSON () method to obtain the server returns, so there is no need for the eval () method, because this time the result is a JSON object, simply call the object can be directly, here to $. GetJSON method for example data processing methods:
$.getJSON("http://blog.snsgou.com/", {param: "snsgou"}, function (data) {
 //The data returned here is already a json object
 //The following other operations are the same as in the first case
 $.each(data.root, function (index, item) {
  if (index == 0) {
   return true; //Countinue returns false and break
  }
  alert("name:" + item.name + ",value:" + item.value);
 });
});

It is important to note that the eval() method in approach 1 executes the string (possibly a js script) dynamically, which can easily cause security problems for the system. So you can use third-party client-side scripting libraries that circumvent eval(), such as JSON in JavaScript, which provides a script library of up to 3k.
 
The second method of parsing is done by using the Function object, which is typically used to parse the return data such as success under AJAX methods in jQuery
var json='{"name":"CJ","age":18}';
data =(new Function("", "return " + json))();

At this point, the data is one that will be parsed into a json object.
 
 
The final conclusion is:
Json string to json object, using (new Function("return "+ jsonString))(); Instead of eval('(' + jsonString + ')');

PS: about json operation, here again for you to recommend a few more practical json online tools for your reference:

Online JSON code verification, verification, beautification, formatting tools:
(link: http://tools.jb51.net/code/json)

JSON online formatting tool:
(link: http://tools.jb51.net/code/jsonformat)

Online XML/JSON interconversion tool:
(link: http://tools.jb51.net/code/xmljson)

Json code online formatting/beautification/compression/editing/conversion tools:
(link: http://tools.jb51.net/code/jsoncodeformat)

Online json compression/escape tool:

(link: http://tools.jb51.net/code/json_yasuo_trans)

C language style /HTML/CSS/json code format beautification tool:
(link: http://tools.jb51.net/code/ccode_html_css_json)


Related articles: