views:

1097

answers:

1

In JavaScript, what are the alternatives of JSON.stringify() for browsers that do not have native JSON support? Thanks

+10  A: 

You should use the library json2.js. It is the basis for the standard JSON.stringify(...) that some browsers include natively.

You can find the page it originated from here: http://www.json.org/js.html

The script automatically makes sure it only adds a JSON.stringify(...) method if it doesn't already exist so there is no danger including it in a browser that has it.

Dan Herbert
But it doesn't fix discrepancies in native implementations, does it?
kangax
I'm not aware of any specific discrepancies in native implementations, but no, it does not fix them. What the script does is checks if the method exists. If it doesn't it adds it, otherwise it leaves it alone.
Dan Herbert
JScript's JSON bugs - http://blogs.msdn.com/jscript/archive/2009/06/23/native-json-support-in-ie8-and-tracking-the-ecmascript-fifth-edition-draft-specification.aspx Mozilla and WebKit ones can be found at corresponding bug trackers.
kangax
If you're concerned about discrepancies, your best option is to modify the source of `json2.js` and make it overwrite the native implementation even if it does exist. This will ensure serialization will behave the same regardless of the browser.
Dan Herbert
Yep, that's one way. It's sad to overwrite fast native implementation, but the benefit is consistent results everywhere. Another possibility is to use native JSON (when available) but fix any known discrepancies, such as those in JScript implementation.
kangax