Javascript eval fails on complicated json array

449 views Asked by At

I want to convert a json string to object by eval, but it fails with error like:

Uncaught SyntaxError: Unexpected identifier VM250:1

below is my string: '[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}]';

Seems there is something wrong in the bold part, but i don't know how to fix it The code below is not working

var m='[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}]';
eval(m);

The code below is working so i think the data structure of this json string is ok

var m=[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}];
alert(m[0].option_in_json);

Also tried with $.parseJSON with no luck

1

There are 1 answers

1
Felix Kling On

It does not work because you are not escaping the data inside the string literal correctly. Look at the value of m in the first case, especially the quotation marks:

[{"option_in_json":"[{"option":"1","is_answer":false}]","question":"1+1"}]
//                 ^  ^

I removed some irrelevant data. You should be able to see that this cannot be valid JavaScript (or JSON), because the quotation mark before option terminates the string.

In order to put the data inside a string literal, you should either fix the data so that it doesn't contain nested JSON, or escape \:

'[{"option_in_json":"[{\\"option\\": ... }]"}]'

Better of course if you are not putting it in a string literal in the first place.

var m='[{"quiz_id":"3","_id":"1","option_in_json": [{"option":"1","is_answer":false},{"option":"2","is_answer":true}],"question":"1+1"}]';
//                                                ^-- don't wrap in "" so no need to escape inner double quotes.

console.dir(JSON.parse(m));

enter image description here