Tuesday 30 August 2011

Convert JSON text to object in Javascript

JSON (JavaScript Object Notation) is lightweight data-interchange structure which is fairly easy for human to read/write as well as for computer to process. GO here if you know more about it.

There are 2 cheap ways to consume JSON using javascript without a need of any 3rd party library. One is eval() function which is very fast. However it also compile and execute any javascript and impose potential security issue.
 

   function toObject(jsonText){
      return eval(jsonText);
   }

 

If this concerns you, a JSON parser should be used indeed. In browsers that provide native JSON support, call JSON.parse() function.

 

   function toObject(jsonTextn){
      return JSON.parse(jsonText);
   }

 

No comments:

Post a Comment