1

Possible Duplicate:
Why the open quote and bracket for eval('(' + jsonString+ ')') when parsing json string

According to the Wikipedia entry on JSON, if you wanna parse a JSON object with eval, say:

{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25
}

You need to do it by:

var obj = eval("(" + JSON + ")");

Without the parentheses wrapping around the JSON text, it will trigger an ambiguity in JavaScript's syntax.

I am not very sure about what this ambiguity is, and would appreciate some input.

Community
  • 1
  • 1
gsklee
  • 4,774
  • 4
  • 39
  • 55
  • Another duplicate: [Why does JavaScript's eval need parentheses to eval JSON data?](http://stackoverflow.com/questions/964397/why-does-javascripts-eval-need-parentheses-to-eval-json-data/964437#964437) – Kobi Jul 25 '11 at 06:20

1 Answers1

0

I don't know if I'd call it an "ambiguity". JSON is just a javascript (really ECMAScript) object literal, so it looks like "{...}". However, in ECMAScript, a statement can't start with a curly brace "{" character.

So a grouping operator is added to make the expression "({...})". That removes the syntax error so it can be passed to eval.

Also, eval'ing code will mean that many errors are just swallowed, you'll find it very hard to debug if there are errors and the string is anything substantial.

RobG
  • 142,382
  • 31
  • 172
  • 209