1

I'm getting an error [Exception: SyntaxError: Unexpected token :] when I try to evaluate the following expression:

eval("{"T1": [1,2,3,4,5,6,7,8,9,10,11,12], "T2": [12,11,10,9,8,7,5,4,3,2,1]}")

However, the same expression without the " works:

eval({"T1": [1,2,3,4,5,6,7,8,9,10,11,12], "T2": [12,11,10,9,8,7,5,4,3,2,1]})

If my JSON is in string format, like in the first example, how can I convert it into a javascript object?

If I try using:

JSON.parse("{"T1": [1,2,3,4,5,6,7,8,9,10,11,12], "T2": [12,11,10,9,8,7,5,4,3,2,1]}")

I get [Exception: SyntaxError: Unexpected identifier]. How can I escape the "?

Paul
  • 3,725
  • 12
  • 50
  • 86
  • 1
    Perhaps you could use something from here: [Link](http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – Mizuho Mar 29 '12 at 15:52
  • 3
    That isn't JSON. If it was, T1 and T2 would be surrounded by `"` not `'`. Fix that and use a real JSON parser, not `eval`. – Quentin Mar 29 '12 at 15:53

4 Answers4

5

Avoid using eval (see why), use JSON.parse when available. To support older browsers, I suggest using a third-party library like Crockford's.

On your second example, it works because there is nothing to be parsed, you already have an object.

EDIT: you added one more question, here is the answer: you escape " with \. For example, this is a valid string containing just a quote: "\"".

Community
  • 1
  • 1
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
3

The curly braces are interpreted to be a code block, not a object delimiter. Therefore you'll get an exception for the colon.

You can work around that by surrounding your object with (), but better use JSON.parse. Don't forget: eval is evil :-)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

You need parentheses, but really, use JSON.parse as bfavaretto suggested.

To understand why your current code is failing, consider that

eval("{}")

runs the program

{}

which is just a block containing no statements while

eval("({})")

runs the program containing a single statement which evaluates the expression {}, an empty object.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
0

What's the point of just evaluating an json object without actually assigning it to any variable?

It seems kind of pointless to me.

eval isn't a dedicated json parser. It's JS parser and it's assuming that the {} is a block of code.

This however works

eval("var abc = {'T1': [1,2,3,4,5,6,7,8,9,10,11,12], 'T2': [12,11,10,9,8,7,5,4,3,2,1]};");

As everyone stated, use JSON.parse if you really need to parse json. Eval is dangerous.

KDV
  • 730
  • 1
  • 6
  • 12