Reputation: 2975
In JavaScript, what are the alternatives of JSON.stringify()
for browsers that do not have native JSON support? Thanks
Upvotes: 26
Views: 60868
Reputation: 398
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:
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.
Upvotes: 0
Reputation: 103397
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.
Upvotes: 41