SoFunction
Updated on 2025-04-06

The best way to convert JSON strings into JSON objects in js

There are generally two ways to parse JSON strings into JSON data format in JSON:
1. One is to use the eval() function.
2. Use Function object to perform return parsing.
 
The first method of parsing: use the eval function to parse, and use the jQuery's each method to traverse
The method of parsing JSON data with jQuery is used as the transmission object for jQuery asynchronous request. The result returned after jQuery request is a json object. The server returns a string in the form of JSON form. The same is true for JSON objects encapsulated using plug-ins such as JSONObject. This is similar to this. I will not explain it here.
Here we first give the JSON string set, the string set is as follows:

Copy the codeThe code is as follows:
var data = " {
root:
    [
        {name: '1', value: '0'},
{name: '6101', value: 'Beijing'},
{name: '6102', value: 'Tianjin'},
{name: '6103', value: 'Shanghai'},
{name: '6104', value: 'Chongqing City'},
{name: '6105', value: 'Weinan City'},
{name: '6106', value: 'Yan'an City'},
{name: '6107', value: 'Hanzhong City'},
{name: '6108', value: 'Yulin City'},
{name: '6109', value: 'Ankang City'},
{name: '6110', value: 'Shangluo City'}
    ]
}
";

Here, based on the data types obtained by jQuery asynchronously - json objects and strings, we introduce the two methods of processing the results obtained.
1. For the JSON string returned by the server, if the jQuery asynchronous request does not provide type description or is accepted as a string, then objectification processing is required. The method is not too troublesome, just put the string in eval() and execute it once. This method is also suitable for obtaining json objects in ordinary JavaScript. The following examples are shown:
Copy the codeThe code is as follows:
var dataObj = eval("(" + data + ")");  // Convert to json object

 
Why do you need to add "("("(" + data + ")");" to eval?
The reason is: the problem with eval itself. Since json starts and ends in the form of "{}", in JS, it will be processed as a statement block, so it must be converted into an expression in a mandatory manner.
The purpose of adding parentheses is to force the eval function to force the expression in brackets to be converted into objects when processing JavaScript code, rather than to execute as statements. For example, for example, if the object literal {} is not added with outer brackets, then eval will recognize the braces as the start and end marks of the JavaScript code block, and then {} will be considered to be executing an empty statement. So the following two execution results are different:
Copy the codeThe code is as follows:

alert(eval("{}"); // return undefined
alert(eval("({})");// return object[Object]

For this writing method, you can see it everywhere in JS.
For example: (function(){})(); When doing closure operations, etc.
Copy the codeThe code is as follows:
alert();//The number of sub-objects output to root
$.each(, fucntion(idx, item) {
 if (idx == 0) {
  return true;
 }

//Output the name and value of each root child object
 alert("name:" + + ",value:" + );
})


 
2. For the JSON string returned by the server, if jQuery asynchronously requests to set type (usually this configuration property) to "json", or use the $.getJSON() method to obtain the server return, then the eval() method is not needed, because the result obtained at this time is already a json object, just call the object directly. Here, use the $.getJSON method as an example to illustrate the data processing method:
Copy the codeThe code is as follows:
$.getJSON("/", {param: "snsgou"}, function (data) {
// The data returned here is already a json object
// The following other operations are the same as the first case
 $.each(, function (index, item) {
  if (index == 0) {
return true; // Same country, return false and break
  }
  alert("name:" + + ",value:" + );
 });
});

It is particularly important to note here that the eval() method in Method 1 dynamically executes the string (probably a js script), which can easily cause system security problems. Therefore, some third-party client script libraries that evade eval() can be used, such as JSON in JavaScript that provides a script library that does not exceed 3k.
 
The second analysis method: use Function object to complete. Its typical application is the analysis of return data data under the AJAX method in jQuery
Copy the codeThe code is as follows:
var json='{"name":"CJ","age":18}';

data =(new Function("", "return " + json))();


At this time, data will be parsed into a json object.
 
 
The final conclusion is:
To convert json string to json object, use (new Function("return " + jsonString))(); instead of eval('(' + jsonString + ')');;

PS: Regarding json operation, here are some practical json online tools for your reference:

Online JSON code verification, inspection, beautification and formatting tools:
http://tools./code/json

JSON online formatting tool:
http://tools./code/jsonformat

Online XML/JSON mutual conversion tool:
http://tools./code/xmljson

json code online formatting/beautification/compression/editing/converting tools:
http://tools./code/jsoncodeformat

Online json compression/escaping tools:

http://tools./code/json_yasuo_trans

C language style/HTML/CSS/json code formatting and beautification tools:
http://tools./code/ccode_html_css_json