Saturday, 1 September 2018

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
<!DOCTYPE html>

<html>

<head>
    <title>Serialization</title>
</head>

<body>
    <script type="text/javascript">
        function displayObject(obj) {
            document.write("<br />");
            for (prop in obj) {
                document.write(prop + " : " + obj[prop] + "<br />");
            }
            document.write("<br />");
        }

        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("<br />Serialized data is " + serializedData + " <br /><br />");

        var emp2 = JSON.parse(serializedData);

        document.write("emp2 details");
        displayObject(emp2);
    </script>
</body>

</html>


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

No comments:

Post a Comment