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