Wednesday, 17 July 2013

Convert a JSON text into a JavaScript object

To convert a JSON text (i.e. a string formatted as JSON) into a JavaScript object, use  the eval() function.

Approach 1:


In this approach you should surround the JSON with parentheses. The reason for the parentheses is so the eval statement treats the text as an object initializer, rather than some other type of code.

var jsonstr='{"name":"Adis","age":25,married:false}';
var jsobj=eval("(" + jsonstr + ")");


OR

Approach 2:

The second approach is to include the variable assignment as the left side of the expression and the JSON as the right, within the eval method:

var jsonstr='{"name":"Adis","age":25,married:false}';
eval("var jsobj=" + jsonstr);

No comments:

Post a Comment

document.write() overwrites the entire page

document.write is a function which basically outputs whatever is given to it. But sometimes, improper usage may overwrite the entire page d...