ECMA262Edition5 provides native JSON support. JSON. parse is used to convert a string to json. See ECMA262Edition515.12.2. See also: This method has been implemented in IE8/Firefox3.5 +/Chrome4/Safari4/Opera10 three methods of String Conversion to json. The usage is simple:
The Code is as follows:
Var str = '{"name": "jack "}';
Var json = JSON. parse (str );
Alert (json. name );
"Jack" is displayed in the browser that implements this method ".
If you add a method for parsing json to Object. prototype (someone may strongly disagree that this method has contaminated the native Object, which is purely for discussion here)
The Code is as follows:
Object. prototype. parseJSON = function (){
Return JSON. parse (this );
}
Because all objects inherit the Object method, this can be used directly,
The Code is as follows:
Var str = '{"name": "jack "}';
Var json = str. parseJSON ();
Alert (json. name );
In str. parseJSON (), this in parseJSON points to str. At this time, not all browsers can be parsed successfully.
In IE8, Firefox, Safari, and Opera, "jack" is still displayed. In Chrome, the following error occurs: Uncaught illegal access.
Why is it not supported to write Chrome like this? Two methods are compared. One parameter passed to JSON. parse is the string str and the other is this. Seems there is no difference between the two?
When str. parseJSON (), this inside parseJSON points to str. Modify the parseJSON method:
The Code is as follows:
Object. prototype. parseJSON = function (){
Alert (typeof this );
Return JSON. parse (this );
};
Run the command again and you will find that the parseJSON pop-up object is displayed. This may be the difference. You can directly create a new string to see the obvious effect.
The Code is as follows:
Var js = JSON. parse (new String ('{"name": "jack "}'));
Alert (js. name );
In addition to the Chrome error, the preceding code runs normally in other browsers.
Conclusion:
In Chrome, the first parameter of JSON. parse can only be a String, not an object (including the new String method is not supported)
Return to the above and add a method to parse json to Object. prototype. to be compatible with all browsers, write as follows:
The Code is as follows:
Object. prototype. parseJSON = function (){
Return JSON. parse (this. toString ());
}
Var str = '{"name": "jack "}';
Var json = str. parseJSON ();
Alert (json. name );
: The BUG has been fixed in Chrome6.