This article mainly introduces three methods for parsing JSON data in JavaScript. This article describes the eval () method, newFunction method, JSON. parse () method and other three methods. For more information, see
Overview
At present, the JSON format is becoming more and more important in web development. Especially in the Process of ajax development projects, it is often necessary to return json strings to the front-end, the front end is parsed into a JS object (JSON ).
The JSON concept in ECMA-262 (E3) was not written to the standard, and the JSON concept in ECMA-262 (E5) was formally introduced, including the Global JSON object and the toJSON method of Date.
Three methods for parsing JSON data
Eval () method
The most common method to parse JSON data is to use javascript's eval () method. The Code is as follows:
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
The Code is as follows:
Function toJson (str ){
Var json = (new Function ("return" + str ))();
Return json;
}
JSON. parse () method
This method only supports IE8/Firefox3.5 +/Chrome4/Safari4/Opera10 or later versions. These browsers are close to W3C standards and the toJSON method is implemented by default.
The Code is as follows:
Function toJson (str ){
Return JSON. parse (str );
}
Json2.js selects the native version when the browser supports JSON. parse native, And it is API compatible with ES5. When ES5 is not fully popularized, John Resig recommends json2.js to use APIs compatible with ES5, it can be smoothly transitioned to ES5 in the future-as long as an import is removed, it will be replaced.