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

Source: Internet
Author: User
Tags eval json opening and closing tags

  This article mainly introduces the best way to convert JSON strings into JSON objects in JS, and need friends to refer to the following

In JS, the JSON string is parsed into JSON data format, usually in two ways: 1. One is to use the Eval () function. 2. Use function objects to perform return parsing.   The first parsing method: Using the Eval function to parse, and using each of the jquery methods to parse the JSON data in jquery, as the transmission object of the jquery asynchronous request, the result of the jquery request returned is the JSON object, Here the server returns the form of a JSON-like string, which is similar to a JSON object encapsulated by a plug-in such as Jsonobject, which is no longer explained here. Here we first give a set of JSON strings, and the string set is as follows:     code is as follows: var data = "{root:     [        {name: ' 1 ', Valu E: ' 0 '},         {name: ' 6101 ', Value: ' Beijing '},    ,     {name: ' 6102 ', Value: ' Tianjin ' },         {name: ' 6103 ', Value: ' Shanghai '},    ,     {name: ' 6104 ', Value: ' Chongqing '}, &NB Sp       {name: ' 6105 ', Value: ' Weinan '},         {name: ' 6106 ', Value: ' Yanan '},         {name: ' 6107 ', Value: ' Hanzhong '},         {name: ' 6108 ', Value: ' Yulin '},     &NBSP ;   {name: ' 6109 ', Value: ' Ankang '},         {name: ' 6110 ', Value: ' Shangluo '}    ]} '; The number of asynchronously fetched here in jqueryAccording to the type--json object and string, we introduce the result processing method obtained by two methods respectively. 1. For the JSON string returned by the server, if the jquery asynchronous request does not have a type description, or is accepted as a string, it needs to be done at once, either in a cumbersome manner or in an eval (). This is also a good way to get JSON objects in a common Javascipt way, as illustrated in the following example:    code: 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 with "{}", in JS it is treated as a block of statements, so it must be coerced into an expression. The purpose of parentheses is to force the Eval function to force an expression in parentheses (expression) into an object when processing JavaScript code instead of executing as a statement (statement). For example, an object literal {}, if the outer bracket is not added, Eval recognizes the curly braces as the opening and closing tags of the JavaScript code block, then {} will be considered to have executed an empty statement. So the following two execution results are different: The code is as follows: Alert (eval ("{}");//return undefined alert (eval ("({})");//return object[object] for this type of writing, in JS, can see everywhere. such as: (function () {}) ();   When doing closure operation. The code is as follows: Alert (dataObj.root.length)//output root number of child objects   $.each (Dataobj.root, fucntion (IDX, item) { if (idx = 0) {& nbsp return true; &NBSP}    //output the name and value of each root child    alert ("Name:" + Item.name + ", Value:" + Item.value);})     2, for the JSON string returned by the server, if the jquery asynchronous request sets the type (typically this configuration property)To "JSON", or use the $.getjson () method to get the server back, then the eval () method is not needed, because the result is already a JSON object, just call the object directly, here the $.getjson method for example to illustrate the data processing method:   Code as follows: $.getjson ("http://blog.snsgou.com/", {param: "Snsgou"}, function (data) { //The data returned here is already a JSON object  //the following other operations in the first case  $.each (data.root, function (index, item) {  if (index = = 0) {   return true; With Countinue, returns false with break  }   alert ("Name:" + Item.name + ", Value:" + item.value);  }); }); In particular, it is important to note that the eval () method in mode 1 executes the string (possibly the JS script) dynamically, which can easily cause a system security problem. So you can use a few 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 a Function object to complete, its typical application is in jquery in the Ajax method of success, etc. for the return data of the parsing code as follows: Var json= ' {name ': ' CJ ', ' age ' : 18} ';   data = (new Function ("", "return" + JSON)) ();   Data at this point is the one that will parse into a JSON object.     The final conclusion is: JSON string to the JSON object, using (New Function ("return" + jsonstring)) (); Instead of eval (' + jsonstring + ');

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: info-contact@alibabacloud.com 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.