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:
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" };
We create another object where we are going to have the
toJSON()
function:var customToJSON = { "firstname":"John", "lastname":"Doe", "email":"john.doe@example.com", toJSON: function () { return {"custom":"rendering...