Paul
Paul

Reputation: 3954

Syntax error on eval() with json as string

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 "?

Upvotes: 1

Views: 8364

Answers (4)

bfavaretto
bfavaretto

Reputation: 71908

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: "\"".

Upvotes: 5

KDV
KDV

Reputation: 730

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.

Upvotes: 0

Bergi
Bergi

Reputation: 664405

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 :-)

Upvotes: 3

Mike Samuel
Mike Samuel

Reputation: 120506

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.

Upvotes: 1

Related Questions