In JavaScript, what are the alternatives of JSON.stringify()
for browsers that do not have native JSON support? Thanks
views:
1097answers:
1
+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
2009-09-26 03:57:04
But it doesn't fix discrepancies in native implementations, does it?
kangax
2009-09-26 20:45:34
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
2009-09-26 23:59:19
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
2009-09-27 17:27:14
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
2009-09-27 17:57:41
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
2009-09-27 20:40:01