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

Source: Internet
Author: User
Tags string to json

In JS to parse the JSON string into JSON data format, generally there are two ways: 1. One for the use of the Eval () function. 2. Use the function object for return parsing.

The first parsing method: Using the Eval function to parse, and using jquery's each method to traverse the method of parsing JSON data with jquery, as a transport object of the jquery asynchronous request, the result of the jquery request is a JSON object, Here, the server returns the form of a JSON-like string, which is similar to JSON objects encapsulated by plug-ins such as Jsonobject, and is no longer explained here. Here we first give a set of JSON strings, the string set as follows:

The code is as follows:

var data = " {root:    [        {name: ' 1 ', Value: ' 0 '},        {name: ' 6101 ', Value: ' Beijing '},        {name: ' 6102 ', V Alue: ' Tianjin '},        {name: ' 6103 ', Value: ' Shanghai '},        {name: ' 6104 ', Value: ' Chongqing '},        {name: ' 6105 ', Value: ' Weinan '},        {name: ' 6106 ', Value: ' Yanan '},        {name: ' 6107 ', Value: ' Hanzhong '},        {name: ' 6108 ', Value: ' Yulin '},        {name: ' 6109 ', V Alue: ' Ankang '},        {name: ' 6110 ', Value: ' Shangluo '}    ]}";

This is based on the data type obtained by jquery asynchronously,--json object and string, and describes how the results are handled in two ways. 1, for the JSON string returned by the server, if the jquery asynchronous request did not do type description, or as a string to accept, then need to do an object processing, the way is not too cumbersome, is to put the string in eval () to execute once. This is also a good way to get JSON objects in a normal Javascipt way, as illustrated below:

The code is as follows:

var dataobj = eval ("(" + Data + ")");  // convert to JSON object

Why eval here to add "(" ("+ Data +") "); The reason is that eval itself is a problem. Since JSON starts and ends in the form of "{}", in JS, it is treated as a block of statements, so it must be coerced into an expression. The purpose of the parentheses is to force the Eval function to force the expression in parentheses to be converted to an object while processing the JavaScript code, rather than being executed as a statement (statement). For example, if the object literal {} is not enclosed, then eval will recognize the curly brace as the start and end tag of the JavaScript block, and {} will be considered an empty statement. So the following two execution results are different:

The code is as follows:

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

For this kind of writing, in JS, you can see everywhere.  such as: (function () {}) (); Do the closure operation and so on.

The code is as follows:

alert (dataObj.root.length); //        if (idx = = 0) {return true;}  //  Alert ("Name:" + + ", Value:" + Item.value);})

2, for the JSON string returned by the server, if the jquery asynchronous request to the type (typically this configuration property) is set to "JSON", or use the $.getjson () method to get the server back, then the eval () method is not required, Because the result is already a JSON object, just call the object directly, here $.getjson method as an example to illustrate the data processing method:

The code is as follows:

function//  The data returned here is already a JSON object //  The following other operation is the first case function (Index, item) {  if (index = = 0)   {returntrue//  with Countinue, return false withbreak  }  alert ("name:" + + ", Value:" +  Item.value); });});

In particular, it is important to note that the eval () method in mode 1 is the dynamic execution of strings (possibly JS scripts), which can easily cause system security problems. So you can use some third-party client script libraries that circumvent eval (), such as JSON in JavaScript, which provides a script library of no more than 3k.

The second parsing method: Using the Function object to complete, its typical application is in jquery in the Ajax method of success and so on the return data of the parsing

The code is as follows:

var json= ' {"name": "CJ", "Age": +} '= (new Function ("", "return" + JSON));

The data at this point is the one that will parse into a JSON object.

The final conclusion is: JSON string to JSON object, using (New Function ("return" + jsonstring)) (); Instead of eval (' (' + jsonstring + ') ');


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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.