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; }
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; }
3, use the global JSON object, as follows:
The code is as follows:
function strToJson(str){ return JSON.parse(str); }
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
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!