Home  >  Article  >  Web Front-end  >  Special implementation of JSON.parse in Chrome_json

Special implementation of JSON.parse in Chrome_json

WBOY
WBOYOriginal
2016-05-16 18:12:091170browse

IE8/Firefox3.5/Chrome4/Safari4/Opera10 has implemented this method. The usage is very simple:

Copy code The code is as follows:

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)
Copy code The code is as follows:

Object.prototype.parseJSON = function () {
return JSON.parse(this);
}

Because all objects inherit the methods of Object, you can use them directly at this time,
Copy code The code is as follows:

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:
Copy code The code is as follows:

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
Copy the code The code is as follows:

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:
Copy code 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);

2010-10-09: This BUG has been fixed in Chrome 6.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn