Why is this line unique?

JSON.parse('["foo", "bar\\"]'); //Uncaught SyntaxError: Unexpected end of JSON input 

When I look at the above code, everything seems to be grammatically correct. I suggested that the JSON string could be converted back to an array containing the string "foo" and the string "bar", since the first backslash skips the second backslash.

So why is there an unexpected end to input? I guess this has something to do with backslashes, but I can't figure it out.

+5
source share
2 answers

It seems that your code should be:

 JSON.parse('["foo", "bar\\\\"]'); 

Your Json object is indeed ["foo", "bar\\"] , but if you want it to be represented in JavaScript code, you need to output the \ characters again, thus having four \ characters.

Yours faithfully

+4
source

You need to double the escape. Using template literals and String.raw you can do:

 JSON.parse(String.raw`["foo", "bar\\"]`); 
0
source

All Articles