Saturday, August 3, 2013

Converting the JSON text to Javascript Object

Converting the JSON text to Javascript Object:


We can use two approaches eval function or JSON parser 

Eval function:


var jsonText="{success:false,error: 'Invalid Data'}"  
var dataObject = eval('(' + jsonText+ ')');  
The properties can be accessed from dataObject. 
var errorMessage=dataObject.error; 
The eval function is very fast. However, it can compile and execute any 
JavaScript
program so this may create security issue, if the JSON text source is trustable
the eval function can be used 

JSON Parser:

var dataObject= JSON.parse(jsonText); 
Converting the Object to JSON String:  
var jsonText= JSON.stringify(dataObject);