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}