JSONWeave

JSONWeave / Guides

Processed entirely in your browser

JSON escape characters and string escaping explained

By Abhishek Jaiswar ยท Published

To escape text for JSON, put a backslash before the double quote and the backslash, and write control characters such as a newline as \n. Most escaping bugs come from encoding twice or not at all.

Open JSON in JSONWeave

What 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

Escape a string in code

Use your language's JSON encoder instead of replacing characters by hand. It escapes quotes, backslashes and control characters for you, which is the safe way to escape quotes and newlines in JSON. Python's json.dumps also writes non-ASCII characters as \uXXXX unless you pass ensure_ascii=False.

JavaScript
JSON.stringify('He said "hi"\n')
// "He said \"hi\"\n"
Python
print(json.dumps('He said "hi"\n'))
# "He said \"hi\"\n"

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.

JSON inside a string
{"payload": "{\"id\": 7, \"ok\": true}"}
Inner value after parsing it again
{"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.
  • "Bad control character in string literal" or "Invalid control character" means a raw newline or tab sits inside a string. Write it as \n or \t.
  • "Invalid escape character" or "Bad escaped character" means a backslash is followed by a character JSON does not define, such as \d in a regular expression. Double the backslash: \\d.
  • 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