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:
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
function strToJson(str){
var json = (new Function("return " str))();
return json;
}
3, use the global JSON object, 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:
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