Three methods for parsing JSON data in JavaScript

  • 2020-07-21 06:45:55
  • OfStack

An overview of the

Nowadays, JSON format is getting more and more attention in web development, especially in ajax development projects, it is often necessary to return json format strings to the front end, which is parsed into JS objects (JSON).
ECMA-262 (E3) did not include the JSON concept in the standard. Fortunately, the JSON concept was formally introduced in ECMA-262(E5), including the global JSON object and toJSON method of Date.
Three ways to parse JSON data

eval () method

The most common way to parse JSON data is to use the eval() method of javascript, as follows:


function toJson(str){
 var json = eval('(' + str + ')');
 return json;
}

This method has performance and security problems and is not recommended.
new Function method

function toJson(str){
 var json = (new Function("return " + str))();
 return json;
}

JSON. parse () method
This method only support IE8 / Firefox3. 5 + / Chrome4 / Safari4 / Opera10 version above, these browsers are close to W3C standard, the default implementation toJSON methods.

function toJson(str){
 return JSON.parse(str);
}

json2.js will use the native version when the browser supports ES54en.parse natively and it is API compatible with ES5. As ES5 is not yet fully popular, John Resig is recommended for json2.js is mainly for the purpose of using API compatible with ES5 now and making a smooth transition to ES5 in the future -- just remove one import and replace it.


Related articles: