Home > Web Front-end > JS Tutorial > Three ways to convert string to json in js

Three ways to convert string to json in js

PHPz
Release: 2018-10-11 14:55:01
Original
1138 people have browsed it

In the process of developing projects using ajax, it is often necessary to return json format strings to the front end, and the front end parses them into js objects (JSON).

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

1, eval method analysis, I am afraid this is the earliest analysis 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, new Function form, quite weird. The following

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

Using JSON.parse must strictly abide by JSON specifications. 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 , an exception is thrown in all browsers using JSON.parse and parsing fails. The first two methods are fine.
See also: Special implementation of JSON.parse in Chrome

For more related tutorials, please visit JavaScript video tutorial

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