During Ajax project development, strings in JSON format are often returned to the front end, and the front end is parsed into JS objects (JSON ).
The JSON concept was not written to the standard in ECMA-262 (E3), but in ECMA-262 (E5) The JSON concept was 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.
View sourceprint?
1 |
Function Strtojson (STR ){ |
2 |
VaR JSON = eval ( '(' + STR + ')' ); |
Remember the parentheses on both sides of Str.
2. The new function format is weird.
View sourceprint?
1 |
Function Strtojson (STR ){ |
2 |
VaR JSON = ( New Function ( "Return" + Str ))(); |
3. Use a global JSON object.
View sourceprint?
1 |
Function Strtojson (STR ){ |
2 |
Return JSON. parse (STR ); |
Currently, IE8 (s)/firefox3.5 +/chrome4/safari4/opera10 has implemented this method.
JSON. parse must comply with JSON specifications strictly. If attributes are enclosed by quotation marks
View sourceprint?
1 |
VaR STR = '{Name: "Jack "}' ; |
2 |
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.