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.

Why JSON?

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() {

            console.log(this.names[0]);

            console.log(this.names[1]);

            console.log(this.names[2]);

  }

} 
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,
>JSON.stringify('abc');
   ""abc"" 

>JSON.stringify(55);
   "55"

>JSON.stringify(['a','b','c','d']);
   "["a","b","c","d"]"

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.

Examples:
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
JSON.stringify(a,replacer);

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"};

JSON.stringify(a,replacer,null);

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

Space:
   
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
>JSON.stringify(['a','b','c','d','e']);

 "["a","b","c","d","e"]"

>JSON.stringify(['a','b','c','d','e'],null,2);

"[

  "a",

  "b",

  "c",

  "d",

  "e"

]"

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.
JSON.stringify(['a','b','c','d','e'],null,"|--");

"[

|--"a",

|--"b",

|--"c",

|--"d",

|--"e"

]"

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 } };

JSON.stringify(obj);

"11"

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

undefined

JSON.stringify(obj1);

"{"a":5,"b":6}"

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() {});
    Undefined
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];

Console.log(arr);

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

JSON.stringify(arr);

"[1,2,3,null,null]"

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".
>JSON.parse('123');
   123
>JSON.parse('[1,2,3]');
   [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"}'; 

>JSON.parse(text,reviver);

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


0 comments:

Post a Comment

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