Thursday, October 3, 2013

How to evaluate Json string using javascript

The term JSON stand for JavaScript Object Notation.

JSON is one of the popular string based format in which data can be exchanged just like XML.As compared to XML,JSON reduces size of data over the wire.JSON was introduced for JavaScript initially but with rise of AJAX & JQuery JavaScript framework JSON format become industry standard for information exchange.
    There are lot of REST based web services that uses JSON For receiving and sending data to & fro the client application.
     WCF has in build support for REST based web services which exchange data as JSON string..JSON data is easy to parse using any client side or server side language furthermore JSON is platform neutral in sense irrespective of on which platform server or client is both can communicate with each other by speaking in terms of JSON.
  "application/json" is MIME type associated with JSON string.JSON data file usually have .json file extension.JSON has support for array & object and other preliminary type of data like string,Boolean or numerical.Object.attribute is like key value pair with attribute as key while term after attribute followed by : is corresponding value.
      Here is code that demonstrates use of  eval JavaScript native function.when we operate eval on valid Json string we get an object in return,this object contain attributes as per passed Json string in our case IsValid is that attribute hence we got term obj.IsValid which has value 'true'.

Kindly note that javascript function eval was designed to evaluate JavaScript expressions and not as JSON-specific parser.Using eval for parsing JSON string is though not advisable if content of string is not from trusted source as any other JavaScript code maliciously embedded in JSON string will also get executed with eval.

Code below is self explanatory.

<!DOCTYPE html>
<h2>JSON string to javascript object</h2>
   Json Object Value: <span id="JsonVal"></span><br>
var txt = '{"IsValid":"true"}'
var obj = eval ("(" + txt + ")");

No comments:

Post a Comment