IE8/Firefox3.5/Chrome4/Safari4/Opera10 has implemented this method. The usage is very simple:
var str = '{"name ":"jack"}';
var json = JSON.parse(str);
alert(json.name);
will be used in the above browsers that implement this method "jack" pops up.
If you add a method to parse json to Object.prototype (someone may strongly object to doing this and polluting the native object, this is purely for discussion)
Object.prototype.parseJSON = function () {
return JSON.parse(this);
}
Because all objects inherit the methods of Object, you can use them directly at this time,
var str = '{"name":"jack"}';
var json = str.parseJSON();
alert(json.name);
str.parseJSON(), this inside parseJSON points to str. Not all browsers can parse successfully at this time.
IE8/Firefox/Safari/Opera still pops up "jack", while Chrome reports an error: Uncaught illegal access.
Why doesn’t Chrome support it if you write it this way? Comparing the two methods, one of the parameters passed to JSON.parse is the string str and the other is this. There seems to be no difference between the two?
When str.parseJSON(), this inside parseJSON should point to str. Modify the parseJSON method:
Object.prototype.parseJSON = function () {
alert(typeof this);
return JSON.parse(this);
};
Re-execute, you can find that parseJSON pops up object, maybe this That's the difference. You can see obvious effects by directly newing a string
var js = JSON.parse(new String('{"name":"jack"}'));
alert(js.name);
The above code except Chrome error , other browsers run normally.
Basically come to the 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)
Go back to the above and give Object. prototype adds a method for parsing json. If you want to be compatible with all browsers, you can write it like this:
Object.prototype.parseJSON = function () {
return JSON.parse(this.toString());
}
var str = '{"name":"jack "}';
var json = str.parseJSON();
alert(json.name);
2010-10-09: This BUG has been fixed in Chrome 6.