Overview
Now JSON format is getting more and more attention in web development, especially in the process of using ajax to develop projects, it is often necessary to return json format strings to the front end , the front end parses it into a JS object (JSON).
The JSON concept was not written into the standard in ECMA-262 (E3). Fortunately, the concept of JSON was officially introduced in ECMA-262 (E5), including the global JSON object and the Date toJSON method.
Three methods of parsing JSON data
eval() method
The most common method of parsing JSON data is to use the javascript eval() method, the code is as follows :
function toJson(str){ var json = eval('(' + str + ')'); return json; }
This method has performance and security issues and is not recommended.
new Function method
function toJson(str){ var json = (new Function("return " + str))(); return json; }
JSON.parse() method
This method only supports IE8/Firefox3.5+/Chrome4 /Safari4/Opera10 and above, these browsers are close to the W3C standard and implement the toJSON method by default.
function toJson(str){ return JSON.parse(str); }
json2.js will use the native version when the browser natively supports JSON.parse, and it is API compatible with ES5. In the current situation where ES5 has not yet been fully popularized, John Resig recommends using json2.js mainly so that you can use APIs compatible with ES5 now and smoothly transition to ES5 in the future - just remove an import and switch over.
For more related articles on three methods of parsing JSON data in JavaScript, please pay attention to the PHP Chinese website!