javascript - JSON.parse fails with quotation in template literal - Stack Overflow

I'm using Editor.js (which saves the HTML blocks as JSON) to create content on my website and it w

I'm using Editor.js (which saves the HTML blocks as JSON) to create content on my website and it works great unless there is a " in the JSON value.

Data insertion works correctly, but when editing entries containing escaped double quotes (\") within JSON values, JavaScript's JSON.parse fails. For example:

j = JSON.parse(`{"data": "<a href=\"/\">Google</a>"}`);

The above would not parse and will say:

SyntaxError: JSON Parse error: Expected '}'

I've tried with just single quotes and that doesn't work either. I've checked if the JSON is valid and jsonlint says both the JSON I generated with Editor.js is valid and the JSON above is valid.

What am I doing wrong? Again, everything works if as long as I don't have an escaped quote (") in the JSON.

I'm using Editor.js (which saves the HTML blocks as JSON) to create content on my website and it works great unless there is a " in the JSON value.

Data insertion works correctly, but when editing entries containing escaped double quotes (\") within JSON values, JavaScript's JSON.parse fails. For example:

j = JSON.parse(`{"data": "<a href=\"https://www.google/\">Google</a>"}`);

The above would not parse and will say:

SyntaxError: JSON Parse error: Expected '}'

I've tried with just single quotes and that doesn't work either. I've checked if the JSON is valid and jsonlint says both the JSON I generated with Editor.js is valid and the JSON above is valid.

What am I doing wrong? Again, everything works if as long as I don't have an escaped quote (") in the JSON.

Share Improve this question edited Mar 15 at 1:06 Spectric 32.4k6 gold badges29 silver badges54 bronze badges asked Mar 15 at 0:58 OliverOliver 211 silver badge2 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

Escape sequences are still parsed in template literals. \" will not behave differently just because it isn't surrounded by double quotes.

Thus, \" in a template literal becomes ", which yields:

{"data": "<a href="https://www.google/">Google</a>"}

Which is not valid JSON. You have to escape the backslashes too. Use \\".

console.log(JSON.parse(`{"data": "<a href=\\"https://www.google/\\">Google</a>"}`));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744626827a4584630.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信