JSON string escaping explained
By Abhishek Jaiswar ยท Published
A JSON string is wrapped in double quotes and a few characters need a backslash. Most escaping bugs come from encoding twice or not at all.
Open JSON in JSONWeaveWhat must be escaped
Inside a string, the double quote, the backslash and every control character below U+0020 must be escaped.
- \" is a double quote
- \\ is a backslash
- \n is a newline, \r a carriage return, \t a tab
- \b is a backspace, \f a form feed
- \u00e9 is a unicode escape with four hex digits
What does not need escaping
Non-ASCII characters can be written as they are in UTF-8. The forward slash may be written as \/ but does not have to be. A raw line break inside a string is invalid, so multi-line text uses \n.
Double-encoded JSON
A common API pattern stores a JSON document inside a string field. The inner quotes are escaped, and the value looks like a wall of backslashes. Parse the outer document, then parse that string value again.
{"payload": "{\"id\": 7, \"ok\": true}"}{"id": 7, "ok": true}Symptoms of wrong escaping
- Windows paths such as "C:\temp" break, because \t is read as a tab. Write "C:\\temp".
- An "Unterminated string" error often means an unescaped quote ended the string early.
- Visible \n sequences in output mean the text was escaped twice.
Related
Ready to try it on your own JSON?
Open the workspace, paste or drop a file, and nothing leaves your browser.
Open JSON in JSONWeave