Stringify an Object in Javascript

I just Googled (other search engines are available) variations of “javascript convert object to JSON”, assuming that it would be something that is completely straightforward and easy to do, either with basic Javascript or using JQuery, which we have loaded in most of our applications anyway. It turns out basic Javascript can’t do it, and nor can JQuery (although Jquery does have the parseJSON function for parsing a JSON string – jQuery.parseJSON( json )). Thanfully, there is a simple way to do it, but it’s not quite as simple as I’d hoped, if you want to fully support all browsers.

The Simple Way (won’t work in IE7 or below))

JSON.stringify(yourObject);

All ‘modern’ browsers (see exactly which ones here: http://caniuse.com/json, but basically it’s everything except IE7 and below) natively support the JSON object, which allows you use JSON.stringify(object) to convert and object to a JSON string, and JSON.parse(string) to go back the other way. So if you’re not bothered about supporting old versions of IE, you can do it this way.

The marginally more complicated way (for full cross-browser compatibility)

json2.js (available here: https://github.com/douglascrockford/JSON-js) gives you the same stringify and parse functions as above, and is pretty small when minified. It seems to be the best option out there if you want to support the poor souls forced to (I really hoping no-one is choosing to) use IE7 or below.