JSON.parse throws errors while eval doesn't on the same strings. Why?

276 views Asked by At

suppose I have something like

var a = '["\t"]'

If I do

eval('var result = ' + a)

Everything works fine. But if I do

var result = JSON.parse(a)

It throws error: Unexpected token.
Same happens with \b, \f: works with eval, while fails with JSON.parse. Why? Shouldn't the parser behave in the same way when encounters "\t"?

On the other hand, both eval and JSON.parse fail with a \n (as expected), but they also both fail with a \r. Why is this?

I'm a little bit confused with all this so could anybody explain what is going on? If possible with details: how is the parser behaving in the two cases?

2

There are 2 answers

2
Nikhil Aggarwal On

You have to escape \ in the JavaScript string, so you'd end up with

var a = '["\\t"]'

For details, please refer to "http://json.org/"

0
Mulan On

Well that's because it's not valid JSON.

Don't try to write JSON yourself. Instead, use JSON.stringify to properly encode your data.

var json = JSON.stringify(["\t"]);
JSON.parse(json);
//=> ["\t"]