Serializing objects to a JSON string

The reverse of the previous recipe is to serialize JavaScript objects into JSON string. Similarly the same rules about having browser support for JSON applies but again this is not a problem in most of the browsers. One way would be to manually create the string, but that is just a way to error-prone and messy browsers, so we will try out some of the methods available out there.

How to do it...

In the following example we use only JavaScript, so we can place it inside a simple script tag in an HTML file:

  1. First need data in order to serialize it to string, so we will create a simple JavaScript object:
        var someJSON = {
          "firstname":"John",
          "lastname":"Doe",
          "email":"john.doe@example.com"
         };
  2. We create another object ...

Get HTML5 Data and Services Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.