Thursday, 3 September 2015

In Detail : JSON in JavaScript

     JSON stands for JavaScript Object Notation. It is a subset of the object literal notation of JavaScript. Object literal notation is construction of JavaScript object in simple way without use of Object() constructor.


1. It is a plain text format for data storage - as configuration files in web applications.
2. JSON is used to send complex data between the Server and the Browser.
3. A light weight format for data interchanging - web services use JSON for transmission of data back and forth because of its light weight than xml.

How JSON differs from Object literal notation:

Let's see with an example. First I will create a simple JavaScript object and then explain how it differs from a JSON Object.
var anObj = {

  count : 3,

  names : ['speakingcs','sreenath','ulasala'],

  printNames : function() {





anObj.printNames(); // speakingcs sreenath ulasala

Here I have created an JS object, it has 2 properties namely count, names and one method printNames() which prints array values to console.

A normal JS object can contain any type of properties, values and methods. Here count, names are properties and 3, ['speakingcs','sreenath','ulasala'] are values. printNames is a function.

In JSON, each such property is called as key and it must be a double quoted String. So a JSON looks like below

 The datatype of values in JSON are also restricted to following.
• String
• number
• object
• array
• A literal as:    true, false, null

A JSON value looks like below i.e a value can be String, number, object, array, true, false, null, But it cannot be a function.

Let's apply the above rules to convert the object "anObj" to JSON.
var jsonObj = {

    "count" : 3,

    "names" : ['speakingcs','sreenath','ulasala']


There should be no methods.

JavaScript has a global variable called JSON which contains several functions to handle JSON data. The main methods are stringify and parse.

These methods are used to convert JavaScript values to strings and vice versa. In web applications, communication between client (browser) and server happens in plain text format. So the client converts JavaScript value to text using JSON.stringify() method and parses to JavaScript value using JSON.parse() method.

Converting JSON to String:

Method: JSON.stringify(value, [replacer], [space]).
The parameters inside square brackets are optional.It converts any JavaScript value to a String in JSON format i.e double quoted string. Parameters replacer and space are optional.
Value: Any JavaScript value i.e number or String or array or date and so on.
Replacer: Can be a function or an array.
Space: Is a number, used to format the output.

some examples,



Replacer as a function:

Replacer as a function takes two parameters, i.e key and value. Here key represents key in JSON and value represents it's corresponding value. The stringify() method calls replacer on each key and value of JSON object. This method is usually used for changing the values in JSON.

function replacer(key,value) {
    if(typeof value === "number") {
        value *= 2;
   return value;
Let's see how can we use the above function.

value : var a = {"a" : 5, "b" : 6, "c" : "56"};
replacer : replacer(key,value) function declared above
Now call stringify() method

Output : "{"a":10,"b":12,"c":"56"}" // values of keys a & b are doubled.
Replacer as an Array:
Values of an array represents keys of JSON. Stringify() method considers only those keys of JSON, while converting JSON object to String. For exmple,
replacer: var replacer = ['a','b'];

JSON object : var a = {"a" : 5, "b" : 6, "c" : "56"};


Output : "{"a":5,"b":6}"; // c is ignored

You can pass a number or a string as space parameter.
A number as space parameter:
    Call to stringify without space parameter results the output in a single line of text. Let's see an example without space and with space










As you can clearly see, call the stringify method with space value equals 2, resulted the same output with space indentation.

Whenever you pass space parameter, stringify method multiplies the number by the level of indentation and indent the line by as many spaces.

If you pass, space value less than 0 , it will be interpreted as 0 and value greater than 10 will be interpreted as 10.
A string as space parameter:

You can also use a String instead of number as space parameter. Only first 10 characters of the string are used if it length exceeds 10. for example.








If you pass an object as value to stringify() which has toJSON() method, then it uses that method to obtain a value to be stringified.

Object with toJSON() method:
var obj = {a : 5, b : 6, toJSON : function() { return this.a + this.b } };



Object without toJSON() method:
var obj1 = { a: 5, b : 6, abc : function() { return this.a + this.b} } ;




The built-in toJSON() methods in JavaScript are:

 1. Boolean.prototype.toJSON()
 2. Number.prototype.toJSON()
 3. String.prototype.toJSON()
 4. Date.prototype.toJSON()
Unsupported values to JSON.stringify():

Unsupported values are handled in different way by stringify().

1. An unsupported value to stringify() returns undefined instead of a string. >JSON.stringify(function() {});
2. If you pass an object, whose properties are unsupported then it simply ignores. >JSON.stringify({abc: function() {}});
3. If you pass an array, whose values are unsupported, then it treats as null >
var fun1 = function() {};

var fun2 = function() { return "";};

var arr = [1,2,3,fun1,fun2];


[1, 2, 3, fun1(), fun2()]



Converting string to value:

You can convert string data that is coming from server as JavaScript value using JSON.parse() method.
Syntax: JSON.parse(text, [reviver]) - parameter inside square brackets is optional.
Pass only single quoted strings to parse() method. For ex
>JSON.parse('"speakingcs"'); // "speakingcs".
   [1, 2, 3]
>JSON.parse('{"a" : 5, "b" : 6}');
   Object {a: 5, b: 6}
The optional parameter reviver is a function with signature like this.

function reviver(key, value) { …. } // any function name with 2 parameters. It is used to transform parsed data. In the below example, I am going to convert the string values to upper case strings.
function reviver(key,value) {

    if(typeof value === 'string') {

       value = value.toUpperCase();


    return value;


>var text = '{"a" : "abc" , "b" : "cde"}'; 


 o/p: Object {a: "ABC", b: "CDE"}


Post a Comment

Note: only a member of this blog may post a comment.