Dealing with Serialization and deserialization in JavaScript

Object serialization is the process of converting an object’s state to a string from which it can later be restored.

The functions JSON.stringify() and JSON.parse() serialize and restore JavaScript objects. These functions use the JSON data interchange format. JSON stands for “JavaScript Object Notation,” and its syntax is very similar to that of the JavaScript object and array literals.

        
x = {a:5, b:{c:[false,null,""]}}; // Define a test object
y = JSON.stringify(x);            
z = JSON.parse(y); 
               
console.log(y); //Output :{"a":5,"b":{"c":[false,null,""]}} 
console.log(z); //Output :{ a: 5, b: { c: [ false, null, '' ] } }        
    

In the above example, variable y is convert objects into strings.

JSON syntax is a subset of JavaScript syntax, and it cannot represent all JavaScript values. Objects, arrays, strings, finite numbers, true-false, and null are supported and can be serialized and restored. Date objects are serialized to ISO-formatted date strings, but JSON.parse() leaves these in string form and does not restore the original Date object.

JSON.stringify() serializes only the enumerable own properties of an object. If a property value cannot be serialized, that property is simply omitted from the stringified output. Both JSON.stringify() and JSON.parse() accept optional second arguments that can be used to customize the serialization and/or restoration process by specifying a list of properties to be serialized, for example, or by converting certain values during the serialization process.

Deserializing Objects 

To Deserialize a JSON into a JavaScript object, here we will use a common method JSON.parse() method. JavaScript Object Notation is used to exchange data to or from a web server or restful API. The data received from a web server is always a string. In order to use that data, you need to parse the data with JSON.parse() which will return a JavaScript Object or Array of Objects

        
let person ={ "name":"John", "age":40, "car":null };
let str = JSON.stringify(person);
console.log(str);
//deserialization is converting a string to an object
console.log(JSON.parse(str));

//Output
{"name":"John","age":40,"car":null}   //Seralization of object
{ name: 'John', age: 40, car: null }  //Deserialization of object        
    

From the above example, variable str serialize the objects into a string. While in deserialization it converts back into an object using the JSON.parse method.

Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top