Home  >  Article  >  Web Front-end  >  Three ways to parse JSON data in JavaScript_javascript skills

Three ways to parse JSON data in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:51:441260browse

Overview

Nowadays, 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, and the front end parses them into JS objects (JSON).
The concept of JSON 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 Date's toJSON method.
Three ways to parse JSON data

eval() method

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

Copy code 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
Copy code 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 and above. These browsers are close to the W3C standard and implement the toJSON method by default.
Copy code The code is as follows:

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.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn