Home >Web Front-end >JS Tutorial >Three ways to convert strings to json in js_json

Three ways to convert strings to json in js_json

WBOY
WBOYOriginal
2016-05-16 18:11:551017browse

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

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

Copy code The code is as follows:

function strToJson(str){
var json = eval('(' str ')');
return json;
}

Remember not to forget the parentheses on both sides of str.
2. The new Function form is quite weird. As follows
Copy the code The code is as follows:

function strToJson(str){
var json = (new Function("return " str))();
return json;
}

3, use the global JSON object, as follows:
Copy code The code is as follows:

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

Currently IE8(S)/Firefox3.5/Chrome4/Safari4/Opera10 has implemented this method. The following is some information: http://blogs.msdn.com/ ie/archive/2008/09/10/native-json-in-ie8.aspx https://developer.mozilla.org/en/Using_JSON_in_Firefox
Using JSON.parse needs to be strict Comply with the JSON specification. For example, attributes need to be enclosed in quotation marks, as follows:
Copy the code The code is as follows:

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

name is not enclosed in quotes Now, when using JSON.parse, exceptions are thrown in all browsers and parsing fails. The first two methods are fine.
See also: Special implementation of JSON.parse in Chrome
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