admin管理员组文章数量:1415420
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 thoughstr
appears to contain'["foo","bar\\"]'
– Phil Commented Sep 27, 2016 at 3:20
2 Answers
Reset to default 4It 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\\"]`);
本文标签: javascriptWhy is this string unparseableStack Overflow
版权声明:本文标题:javascript - Why is this string unparseable? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745224404a2648542.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论