Gwater17
Gwater17

Reputation: 2314

Why is this string unparseable?

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

When I look at the above code everything seems grammatically correct. It's a JSON string that I assumed would be able to be converted back to an array that contains the string "foo", and the string "bar\" since the first backslash escapes the second backslash.

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

Upvotes: 5

Views: 4373

Answers (2)

SorMun
SorMun

Reputation: 105

It seems like your code should be:

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

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

Regards

Upvotes: 4

MinusFour
MinusFour

Reputation: 14423

You'd need to double escape. With template literals and String.raw you could do:

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

Upvotes: 0

Related Questions