Lolly
Lolly

Reputation: 36412

javascript eval method syntax

I am using jquery in my web application. There we use the below eval method.

    var json = eval('(' + data + ')');

After googling I found eval method used above converts json data to javascript object. But what does that syntax means ? why it has to be enclosed within ('(' ')') parenthesis. Please help me in understanding.

Upvotes: 0

Views: 143

Answers (2)

xdazz
xdazz

Reputation: 160833

Use () to enclose data is to prevent {} to be parsed as a block.

var json = eval('{}');  // the result is undefined
var json = eval('({})');  // the result is the empty object. 

var json = eval('{"a": 1}'); // syntax error
var json = eval('({"a": 1})'); // the result is object: {a: 1}

But you should not use eval to parse json data.

Use var json = JSON.parse(data); or some library functions instead.

Upvotes: 2

Eric
Eric

Reputation: 97571

Don't use eval to parse json. Since you're using jQuery, use $.parseJSON(data). What if data contained window.close()?

WRT to the parentheses, you can see a comment explaining them in douglas crockford's json2.js:

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

Upvotes: 2

Related Questions