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