27

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

2 Answers 2

41

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: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

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.

Sign up to request clarification or add additional context in comments.

8 Comments

But it doesn't fix discrepancies in native implementations, does it?
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.
Which browsers/versions do not have native JSON support?
@JoeCoder Older versions of every browser except Chrome. Specifically, IE7 and older, and Firefox 3.0 and older are lacking support.
@JoeCoder caniuse.com/json <= IE7, <= Firefox 3.0, <= Safari 3.2, <= opera 10.0-10.1
|
0

Depending on your use case, you can use a serialization library.

This is helpful when you want to store (or transfer) more complex Javascript objects without them breaking when you want to parse them back later (among other uses),

However, you won't get a standard JSON file but rather a superset of it that likely can only be used by the same library.

I've listed some of the reasons why you might want to consider a Serializer library instead of JSON.stringify() and JSON.parse(). Every Serializer is different but ideally, a Serializer can:

  1. Handle circular references, which JSON.parse() cannot handle.
  2. Handle all data types including Date, Error, undefined, or Functions - which JSON.stringify can't.
  3. Handle the conversion of non-standard data types.
  4. Deal with much larger objects.
  5. Handle Unicode or other special characters better.

Here's a library that I found easy to use: https://github.com/erossignon/serialijse

As an example use case for Serialization (although there are more prominent use cases and this is just how I used it), I used the minified version of the mentioned library to write a Developer Tools console code snippet to backup all the configurations and storage of a browser extension into a file to restore later. This would not have been possible with JSON.stringify() due to the custom types the extensions had stored in their local storage.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.