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

2
  • 1
    Perhaps you could use something from here: Link Commented Mar 29, 2012 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. Commented Mar 29, 2012 at 15:53

4 Answers 4

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

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

Comments

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

Comments

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.

Comments

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.

Comments

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.