During ajax development projects, strings in json format are often returned to the front end, and the front end is parsed into js objects (JSON ).
ECMA-262 (E3)The JSON concept is not written to the standard.
ECMA-262 (E5)The concept of JSON in is formally introduced, including the Global JSON object and the toJSON method of Date.
1. eval parsing. I'm afraid this is the earliest parsing method. As follows:
The Code is as follows:
Function strToJson (str ){
Var json = eval ('+ str + ')');
Return json;
}
Remember the parentheses on both sides of str.
2. The new Function format is weird. As follows:
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 );
}
At present IE8 (S)/Firefox3.5 +/Chrome4/Safari4/Opera10 has achieved this 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
JSON. parse must comply with JSON specifications strictly. If attributes are enclosed by quotation marks
The Code is as follows:
Var str = '{name: "jack "}';
Var obj = JSON. parse (str); // --> parse error
Name is not enclosed in quotation marks. If JSON. parse is used, an exception is thrown in all browsers and parsing fails. The first two methods are fine.
For details, see the special implementation of JSON. parse in Chrome.