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.

Lolly
  • 34,250
  • 42
  • 115
  • 150

2 Answers2

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.
Eric
  • 95,302
  • 53
  • 242
  • 374
  • 1
    Alternates to jQuery - see [this question](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript). – Paul Fleming Sep 02 '12 at 15:10
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.

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • 1
    `{a: 1}` is not valid JSON. That is actually parsed as a label `a` for an empty expression `1` in a block. – Cristi Mihai Sep 02 '12 at 15:20
  • 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? – Elias Van Ootegem Sep 02 '12 at 15:21