This object can also be passed to JavaScript functions and methods rather than specifying individual arguments. Useful stuff.

However, what if we need to store this object in a cookie? What if we need to pass the object to a web services via an Ajax request? What if that web service wants to return a modified version of the object? The answer is serialization:

Serialization is the process of turning any object into a string.

De-serialization turns that string back into a native object.

Perhaps the best string notation we can use in JavaScript is JSON — JavaScript Object Notation. JSON is a lightweight data-interchange format inspired by JavaScript object literal notation as shown above. JSON is supported by PHP and many other server-side languages (refer to json.org).

There are two JSON methods in JavaScript:

JSON.stringify(obj) — converts an JavaScript object to a JSON string

JSON.parse(str) — converts a JSON string back to a JavaScript object

Unfortunately, very few browsers provide these methods. To date, only Firefox 3.5, Internet Explorer 8.0 and Chrome 3 beta offer native support. Some JavaScript libraries offer their own JSON tools (such as YUI) but many do not (including jQuery).

However, all is not lost — JavaScript is flexible and we can implement the JSON stringify and parse methods whenever a browser requires them.

At the top of our code, we will create a JSON variable that points to the native JSON object or an empty object if it is unavailable:

The use of eval() in JSON.parse is inherently risky. It will not be a problem if you are calling your own web services, but calls to third-party applications could accidentally or intentionally break your page and cause security issues. If necessary, a safer (but longer and slower) JavaScript parser is available from json.org.

I hope you find the code useful. Feel free to use it in your own projects.

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler