Deserialize JSON to instance of JavaScript class

Prototypical class is used to create classes in JavaScript like other programming languages.
The object return from these classes will have corresponding class information. When you to try to serialize and de-serialize this object, the class information associated with the corresponding object will be removed.

In this post, we are going to see how to retrieve this class information and make the object as the instanceof corresponding class.

The process involves two steps. They are

1. Parse using JSON.parse method.
2. Assign the constructor of the actual class to the __proto__ property of the parse JSON.

Let us see this in details.

If we have a JavaScript class like below.

 var myClass = function(){
this.a = 1;
return this.a;
};

var d = new myClass(); //result: "{a:1}";

d instanceof myClass //result: true;

In the above all works fine. The problem will arise if we try to check instanceof on the object from deserialization like shown below.

var str = JSON.stringify(d);

var d = JSON.parse(str); //result: "{a:1}
d instanceof myClass //result: false;

So now d lost its class information and hence it failed. Now we can use the below utility function to retrieve the class information.


var toCalss = function(obj, proto) {
obj.__proto__ = proto;
return obj;
}

var res = toClass(d, myClass.prototype);

res instanceof myCalss //result: true;

Now the object will have class information which makes the instanceof to work as expected.
Happy scripting..

 

Using JSON parse and stringify methods

JSON plays vital role in JavaScript when comes with server interaction. But i noticed when people spoke about JSON they represent it as JSON object in Javascript which is incorrect. JSON is not a object it is just a string format which can be converted to object/array based on its language(Javascript, C#, C++ etc.)

JSON can be converted to JavaScript object using JSON.parse and JSON.stringify vice verse.

JSON.stringify

It is similar to the serialization of the object. The signature of the stringify method is as follows.

JSON.stringify(value[, replacer[, space]])

In the above the first argument is the object/array to be converted to JSON formatted string.

Controlling the stringify operation

Using replacer

The second argument of the stringify method is the replacer which can be an array or function and the value returned from the replacer will be stringify.

Example 1: using array

JSON.stringify({ a:1, b:2, c:null }, ["a","c"]);
//Output: "{"a":1,"c":null}"

Example 2: using function

JSON.stringify({a:1,b:2,c:null}, function(key, value) { return value != null ? value: undefined });
//Output: "{"a":1,"b":2}"
Using toJSON property

It is an another way of customizing the stringify operation. If an object contains a property named toJSON then the value returned from this function will be stringified instead of whole object.


var exFn = function() {
                      this.a=1;
                      this.b=2,
                      this._sum= function() { return this.a + this.b };
                      this.toJSON = function() {
                                             return {
                                                      a:this.a,
                                                      b: this.b,
                                                      sum: this._sum()
                                                     }
                                                }
                    }
//Output: JSON.stringify(new exFn())
"{"a":1,"b":2,"sum":3}"

JSON.parse

It is similar to the de-serialization of the object. The signature of the parse method is as follows.

JSON.parse(text[, reviver])

In the above the first argument is the JSON text input which has to be parsed to JavaScript object/array. For that the JSON string must abide the standards provided by the ECMA-404 The JSON Data Interchange Standard.

Controlling the parse operation

The parse operation can be controlled using the second argument of the parse method. It can be of type function. If the reviver is used then the parse will be done only based on the value returned by the reviver if reviver return undefined then that key will be excluded. The below will exclude the key with null values

var d = "{\"a\":1,\"b\":1,\"c\":null}"
JSON.parse(d, function(key, value){ if(value) return value; });
//Output: Object { a=1,  b=1}