JSON.stringify() array bizarreness with Prototype.js

morgancodes picture morgancodes · Apr 2, 2009 · Viewed 83.1k times · Source

I'm trying to figure out what's gone wrong with my json serializing, have the current version of my app with and old one and am finding some surprising differences in the way JSON.stringify() works (Using the JSON library from json.org).

In the old version of my app:

 JSON.stringify({"a":[1,2]})

gives me this;

"{\"a\":[1,2]}"

in the new version,

 JSON.stringify({"a":[1,2]})

gives me this;

"{\"a\":\"[1, 2]\"}"

any idea what could have changed to make the same library put quotes around the array brackets in the new version?

Answer

Raphael Schweikert picture Raphael Schweikert · Jun 30, 2010

Since JSON.stringify has been shipping with some browsers lately, I would suggest using it instead of Prototype’s toJSON. You would then check for window.JSON && window.JSON.stringify and only include the json.org library otherwise (via document.createElement('script')…). To resolve the incompatibilities, use:

if(window.Prototype) {
    delete Object.prototype.toJSON;
    delete Array.prototype.toJSON;
    delete Hash.prototype.toJSON;
    delete String.prototype.toJSON;
}