Guide
How to escape quotes, backslashes, and newlines in JSON
Learn how to represent quotes, backslashes, newlines, and Unicode characters inside a valid JSON string.
by Tools in a Tab · Published on · Reviewed on
Short answer
Inside a JSON string, write a double quote as \", a backslash as \\, and
a newline as \n. A literal double quote or control character cannot appear
unescaped inside the string: it would either close the string or make the JSON
document invalid.
Common JSON escape sequences
| Character in the value | Representation in JSON |
|---|---|
Double quote " |
\" |
Backslash \ |
\\ |
| Newline | \n |
| Carriage return | \r |
| Tab | \t |
| Backspace | \b |
| Form feed | \f |
A forward slash / can be written directly. JSON also permits \/, but
escaping the slash is normally unnecessary.
Example with quotes and a new line
This object contains a quote in its message and a Windows path:
{
"message": "Ada said: \"ready\"\nNext line",
"path": "C:\\temp\\notes.txt"
}
After parsing, message contains an actual line break between “ready” and
“Next”, while path contains single backslashes. Paste the example into the
JSON validator to check its syntax.
Escape text versus resulting character
The two characters \ and n form the \n escape sequence in the JSON
document. After parsing, the value contains one newline. If the value must
literally contain a backslash followed by the letter n, write \\n in JSON.
The same distinction applies to a path: "C:\\temp" represents C:\temp.
A second layer, such as a JavaScript source string, may require its own escaping.
Avoid counting slashes manually by constructing the value and serializing it:
JSON.stringify({ message: 'Ada said: "ready"\nNext line' });
Unicode and \u sequences
JSON exchanged between systems normally uses UTF-8, so characters such as ñ
or 😀 can appear directly. The \uXXXX notation is also available for UTF-16
code units. Characters outside the basic multilingual plane can be represented
as a surrogate pair, although keeping the Unicode character and relying on a
serializer is usually clearer.
Do not cut a string in the middle of a surrogate pair. Different source forms,
such as "a\\b" and "a\u005Cb", can produce exactly the same parsed value.
Frequent mistakes
- Using single quotes to delimit strings; JSON strings require double quotes.
- Typing a real line break inside a string instead of
\n. - Escaping a value twice after it has already been serialized.
- Confusing
\nwith\\nand getting visible text instead of a new line. - Building JSON through concatenation instead of using a serializer.
Section 7 of RFC 8259 defines JSON strings and their permitted escapes. When the source is a program value, serialize it once and validate the final document rather than an intermediate representation printed by a console.