最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is this string unparseable? - Stack Overflow

programmeradmin2浏览0评论
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.

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.

Share Improve this question asked Sep 27, 2016 at 3:15 Gwater17Gwater17 2,3343 gold badges23 silver badges45 bronze badges 9
  • Why are you doubly escaping the quotes after bar? Do you explicitly need a \ then " in your string? – scrappedcola Commented Sep 27, 2016 at 3:17
  • I'm doing an exercise where this is a test case. – Gwater17 Commented Sep 27, 2016 at 3:18
  • 1 \\" is really \" which means that you are escaping the string and not closing it. – MinusFour Commented Sep 27, 2016 at 3:18
  • 1 Type '["foo", "bar\\"]' into your browser console and see what string that literal actually creates - you'll see it's not valid JSON. – nnnnnn Commented Sep 27, 2016 at 3:18
  • Seems like a string literal problem. For example, this passes ~ str = JSON.stringify('["foo","bar\\"]'); JSON.parse(str); even though str appears to contain '["foo","bar\\"]' – Phil Commented Sep 27, 2016 at 3:20
 |  Show 4 more ments

2 Answers 2

Reset to default 4

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

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

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

评论列表(0)

  1. 暂无评论