0

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.

1
  • 1
    "There we use the below eval method." ... WHY? Commented Sep 2, 2012 at 15:16

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

{a: 1} is not valid JSON. That is actually parsed as a label a for an empty expression 1 in a block.
This is the correct answer as to why your string needs to be enclosed by the brackets. Though: JSON.parse is what you should use, except for IE<9 (doesn't support JSON out of the box. Not to worry: $.parseJSON(data); is X-browser, and since you're using jQuery already, why not use the latter?
2

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.

1 Comment

Alternates to jQuery - see this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.