admin管理员组

文章数量:1388822

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

本文标签: javascriptJSONparse fails with quotation in template literalStack Overflow