How to escape JSON strings
Inside a JSON string, a few characters need a backslash. Getting it wrong causes many parse errors and almost every double-encoded payload.
2 min readUpdated MasterDev
What must be escaped
Only three groups of characters must be escaped inside a JSON string:
- the double quote
", written\" - the backslash
\, written\\ - control characters U+0000 to U+001F, most often line feed
\n, carriage return\rand tab\t; the rest are written as\u0000to\u001f
Everything else may appear as is, including accented letters, Chinese characters and emoji. "café" is valid JSON and needs no escaping.
Optional escapes
Any character may also be written as \uXXXX, and the slash may be written as \/. After parsing, "caf\u00e9" and "café" are the same string. You will see the long form from tools that output ASCII only, such as Python's json.dumps with its default ensure_ascii=True.
The \/ form has one real use: JSON placed inside an HTML <script> tag, where the text </script> would end the tag early.
Putting JSON inside JSON
Webhooks, message queues and log pipelines often carry a payload as a string inside another JSON document. The inner document must be escaped so that its quotes do not end the outer string:
{
"event": "order.created",
"payload": "{\"id\":1042,\"total\":49.9}"
}To read it, parse twice: once for the envelope, once for payload. The Escape button in the formatter does the writing side for you: it turns the whole input into one string literal, ready to paste as a value.
Spotting double encoding
Double encoding is escaping by accident: a value that was already JSON gets serialized again. The symptoms are a response body that starts with "{\", and code where JSON.parse returns a string instead of an object.
app.get('/user', (req, res) => {
res.json(JSON.stringify(user)); // res.json serializes again
});app.get('/user', (req, res) => {
res.json(user);
});The same mistake in Python is passing json.dumps(data) to an HTTP client's json= parameter. Fix it where the data is produced, not by parsing twice on the other side.
Escaping in code
Let a serializer do the escaping. It knows every rule, including the rare control characters that hand-written code forgets.
// JavaScript
const body = JSON.stringify({ message: text });# Python: ensure_ascii=False keeps accents and emoji readable
body = json.dumps({"message": text}, ensure_ascii=False)// Java with Jackson
String body = new ObjectMapper().writeValueAsString(Map.of("message", text));# Shell: jq builds the JSON and escapes the variable
jq -n --arg message "$MESSAGE" '{message: $message}'
# Turn a whole text file into one JSON string
jq -Rs . < notes.txtAvoid printf or string templates such as '{"message": "' + text + '"}': the first quote or line break in text breaks the document, and in the worst case lets the input add fields of its own.
Reading an escaped string back
To turn an escaped string back into the original text, parse it as JSON, quotes included. In a browser console, JSON.parse('"line one\\nline two"') returns the two lines. If the result is itself a JSON document, parse it once more, or paste it into the formatter to read it.