Home > Web Front-end > JS Tutorial > Three ways to parse JSON data in JavaScript

Three ways to parse JSON data in JavaScript

高洛峰
Release: 2017-02-17 16:54:56
Original
1425 people have browsed it

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;
}
Copy after login


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;
}
Copy after login


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);
}
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template