Serializing and Deserializing Objects in JavaScript using JSON

The JavaScript code listed below declares a couple of “classes” (actually, functions) and then instantiates some nested instances of those classes. It then serializes the nested objects to a JSON string, displays that string, and then deserializes that string back into the original nested instances of JavaScript objects. Finally, it serializes the deserialized objects again and displays the resulting string, just to prove that it matches the first one.

To see the code in action, copy it into a .html file and open that file in a web browser that runs JavaScript.

UPDATE 2013/10/31: For a serializer that deserializes strings to actual instances of types, rather than just as generic “objects”, see a more recent post.

<script type='text/javascript'>

function TestClassOne(name, children)
{ = name;
	this.children = children;

function TestClassTwo(name, schmame)
{ = name;

var testObjectBefore = new TestClassOne
	// children
		new TestClassTwo("Two.One"),
		new TestClassTwo("Two.Two"),
		new TestClassTwo("Two.Three"),

var testObjectBeforeAsJSON = JSON.stringify(testObjectBefore);

var newline = "<br />";

document.write("testObjectBeforeAsJSON is: " + testObjectBeforeAsJSON + newline);

var testObjectAfter = JSON.parse(testObjectBeforeAsJSON);

var testObjectAfterAsJSON = JSON.stringify(testObjectAfter);

document.write("testObjectAfterAsJSON is: " + testObjectAfterAsJSON + newline);

This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s