Depending on where you put it,
- In the
<div> , as you requested, you need to make sure that JSON does not contain special HTML files that can run a tag, HTML comment, inline doctype, etc. You need to avoid at least < and & so that the original character does not appear in the escape sequence. - In the
<script> elements you need to make sure that the JSON does not contain the end tag </script> or the escaping of the text border: <!-- or --> . - In event handlers, you need to make sure that JSON retains its value, even if it has objects that resemble HTML objects and do not violate attribute boundaries (
" or ' ).
For the first two cases (and for old JSON parsers) you should encode U + 2028 and U + 2029, since they are newline characters in JavaScript, even if they are allowed in non-JSON encoded strings.
For correctness, you need to avoid the \ and JSON characters, and it will never be a bad idea to always encode NUL.
If HTML can be served without encoding the content, you must encode + to prevent UTF-7 attacks .
In any case, the following table of screens will work:
- NUL →
\u0000 - CR →
\n or \u000a - LF →
\r or \u000d " → \u0022& → \u0026' → \u0027+ → \u002b/ → \/ or \u002f< → \u003c> → \u003e\ → \\ or \u005c- U + 2028 →
\u2028 - U + 2029 →
\u2029
So, the JSON string value for the text Hello, <World>! with a new line at the end will be "Hello, \u003cWorld\u003e!\r\n" .
Mike Samuel Sep 06 2018-11-11T00: 00Z
source share