Serialising A JavaScript Object To JSON

As part of my Draw Something Solver I needed to convert a JavaScript object to a string of JSON data. In the past I’d have resorted to a bit of library code, but as I am coding to a recent version of Safari, I thought I’d try to inbuilt JSON functions available to a modern browser.

The method I needed is JSON.stringify(), and it’s very easy to use.

var text = JSON.stringify(myObject);

The above example serialises myObject into text.

There is an equivilant method, JSON.parse() that can be used to safely take a text JSON string and turn it into an object without relying on JavaScript’s eval() function.

There is a useful chart showing JSON support in modern browsers over at caniuse.com.