Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

JavaScript: Serialize objects

Serialization is the process of converting Object state to string. de-Serialization is a process to bring back the object’s state from string. JavaScript provides JSON.stringify() to serialize the object and JSON.parse() method to deserialize.

serialize.html





Serialization



"text/javascript">
function displayObject(obj) {
document.write("
"
);
for (prop in obj) {
document.write(prop + " : " + obj[prop] + "
"
);
}
document.write("
"
);
}

function Employee(id, firstName) {
this.id = id;
this.firstName = firstName;
}

var emp1 = new Employee(1, "Hari Krishna");
document.write("emp1 details");
displayObject(emp1);

var serializedData = JSON.stringify(emp1);
document.write("
Serialized data is "
+ serializedData + "

"
);

var emp2 = JSON.parse(serializedData);

document.write("emp2 details");
displayObject(emp2);






Open above page in browser, you can able to see following text.


emp1 details
id : 1
firstName : Hari Krishna


Serialized data is {"id":1,"firstName":"Hari Krishna"}

emp2 details
id : 1
firstName : Hari Krishna

What data types of JavaScript are supported while serialization?
Currently JSON syntax is a subset of JavaScript syntax. Objects, arrays, strings, finite numbers, true, false, and null are supported and can be serialized and deserialized.

What about special values NaN, Infinity, -Infinity?
NaN, Infinity, and -Infinity are serialized to null.

How the Date objects serialized?
Serialized in the form of ISO-formatted date strings.

Is there any objects that I can’t serialize?
Function, RegExp, and Error objects and the undefined value cannot be serialized (or) deserialized.

Is non-enumerable properties serialzed?
No, only enumerable properties of an object are serialized.


Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

JavaScript: Serialize objects

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×