Thursday, April 7, 2011

Javascript Modules and Objects– Parsing JSON text

A JSON is a lightweight data-interchange format that is easy for machine to parse and generate and easy for humans to read and write. You can parse JSON string in various language like C#, C++ etc.
 
A JSON string is in the form of {<name>:<value>}.
Following is an example how JSON object is created.   
//## To Create a JSON OBJECT
// A JSON object is created using syntax 
// var objName={<name>:<property>};
var myEntity={
    name:'name1',
    age:25,
    sex:'male',
    dob:'18/06/1980',
    printName:function(){
      alert("Printing name "+name);  //this won't work as JSON object behave like module.
      alert("Printing name with module prefix "+myEntity.name); // this work as JSON object behave like module.
    }
};

The above example shows how to build JSON by using simple entity style.

But what about creating JSON by string parsing. there are two methods of the same

Method 1

eval("var stJSON={ 'name':'abc','age':'23'}");

This is pretty nice but have drawback of having slow performance due to eval and also is easily a candidate for malicious activity.

Method 2

var strJson="return {'name':'abc','age':'23'}";
var strToJsonEntity=new Function(strJson)();

This will do the same task but uses a pretty fine technique. It works by creating a Function which returns the newly created object by passing the body as string. We execute this function to return the newly created object. This is pretty fine technique but require understanding of how Function works.

A JSON object can not have further instance members hence the following call will fail.

var myEntityInstance=new myEntity();

This also means that JSON objects doesn't have prototype property and we can easily validate this by checking this.

alert(myEntity.prototype); //results to null.

Hope this introduction will help us in better understanding JSON behavior in javascript.