ECMA-262 (E3) did not write the JSON concept to the standard, fortunately the concept of JSON in ECMA-262 (E5) was formally introduced, including the global JSON object and the Tojson method of date.
1,eval way to parse, I am afraid this is the earliest way to parse. As follows:
Copy CodeThe code is as follows:
function Strtojson (str) {
var json = eval (' (' + str + ') ');
return JSON;
}
Remember to do not forget the parentheses on both sides of Str.
2,new function form, more strange oh. As follows
Copy CodeThe code is as follows:
function Strtojson (str) {
var json = (new Function ("return" + str));
return JSON;
}
3, use the global JSON object, as follows:
Copy CodeThe code is as follows:
function Strtojson (str) {
return Json.parse (str);
}
At present IE8 (S)/FIREFOX3.5+/CHROME4/SAFARI4/OPERA10 has implemented the method, the following is part of the information: http://blogs.msdn.com/ie/archive/2008/09/10/ Native-json-in-ie8.aspx Https://developer.mozilla.org/en/Using_JSON_in_Firefox
Use Json.parse strict adherence to the JSON specification, such as attributes are required in quotation marks, as follows
Copy CodeThe code is as follows:
var str = ' {name: ' Jack '} ';
var obj = json.parse (str); --Parse Error
The name is not enclosed in quotation marks, and the parsing fails with the exception thrown in all browsers using Json.parse. And the first two ways are fine.
See also: Special implementations of Json.parse in Chrome
Three ways to convert a string into JSON in JS