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

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

programmeradmin2浏览0评论

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>"}`));

发布评论

评论列表(0)

  1. 暂无评论