Home > Web Front-end > JS Tutorial > JS method to convert string string to json object

JS method to convert string string to json object

一个新手
Release: 2017-09-18 10:45:23
Original
2366 people have browsed it

ECMA-262(E3) did not write the JSON concept into the standard. Fortunately, in ECMA-262(E5) the concept of JSON was officially introduced, including The global JSON object and Date's toJSON method.

1, eval method parsing, I am afraid this is the earliest parsing method. As follows:

The code is as follows:

function strToJson(str){ 
var json = eval('(' + str + ')'); 
return json; 
}
Copy after login

Remember not to forget the parentheses on both sides of str.
2, the new Function form is quite weird. The following

The code is as follows:

function strToJson(str){ 
var json = (new Function("return " + str))(); 
return json; 
}
Copy after login

3, use the global JSON object, as follows:

The code is as follows:

function strToJson(str){ 
return JSON.parse(str); 
}
Copy after login

Currently IE8(S)/Firefox3.5+/Chrome4/Safari4/Opera10 has implemented this method
Using JSON.parse must strictly comply with the JSON specification. For example, attributes need to be enclosed in quotation marks, as follows

The code is as follows:

var str = '{name:"jack"}'; 
var obj = JSON.parse(str); // --> parse error
Copy after login

name is not enclosed in quotation marks. When using JSON.parse, an exception is thrown in all browsers and the parsing fails. The first two methods are fine.

The above is the detailed content of JS method to convert string string to json object. For more information, please follow other related articles on 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