Escaping Special Characters in JSON: A Complete Reference
If you have ever encountered a cryptic error like "Unexpected token" or "Bad control character in string literal" when working with JSON, there is a good chance it was caused by an unescaped special character. JSON has strict rules about which characters can appear inside string values and how certain characters must be represented — and violating those rules produces invalid JSON that every parser will reject.
Understanding JSON escaping is essential for anyone who constructs JSON by hand, generates it from templates, or processes user input that gets embedded in JSON strings. In this reference, we will cover every escape sequence the JSON specification defines, walk through practical code examples, and highlight the mistakes that trip up even experienced developers.
What Is Character Escaping in JSON?
Character escaping is the process of representing special characters using alternative sequences so that a parser can distinguish between the character's literal meaning and its structural role. In JSON, string values are delimited by double quotes ("). If you need to include a literal double quote inside a string, you must escape it with a backslash: \". Without escaping, the parser would interpret the inner quote as the end of the string, breaking the structure.
The JSON specification (RFC 8259) defines exactly which characters must be escaped and how. There are no optional escapes in JSON — the rules are universal and every compliant parser enforces them identically.
The Complete JSON Escape Sequence Reference
JSON supports exactly eight named escape sequences, plus a Unicode escape for any character. Here is the full list:
Named Escape Sequences
\\"— Double quote. Required whenever a literal"appears inside a string value.\\\\— Backslash. Required whenever a literal\appears inside a string value.\\/— Forward slash. Optional but sometimes used to prevent</script>injection in HTML contexts.\\b— Backspace (U+0008). Rarely seen in practice.\\f— Form feed (U+000C). A legacy page-break character.\\n— Newline (U+000A). The most commonly escaped character after the double quote.\\r— Carriage return (U+000D). Used in Windows-style line endings (\r\n).\\t— Tab (U+0009). Horizontal tab character.
Unicode Escape Sequences
Any Unicode character can be represented using the \uXXXX syntax, where XXXX is the four-digit hexadecimal code point. For example:
\u0041representsA\u00e9representse(e with acute accent)\u4e16represents世(Chinese character for "world")\u0000represents the null character (U+0000)
Characters outside the Basic Multilingual Plane (code points above U+FFFF) must be represented as a surrogate pair — two consecutive \uXXXX sequences. For example, the emoji character U+1F600 (grinning face) is represented as \uD83D\uDE00.
Characters That MUST Be Escaped
According to RFC 8259, the following characters are required to be escaped when they appear inside a JSON string:
- The double quote
"— must be written as\\" - The backslash
\— must be written as\\\\ - All control characters U+0000 through U+001F — must be escaped using
\uXXXXor named sequences (\n,\t, etc.)
Practical Code Examples
Escaping User Input in JavaScript
When you embed user-provided strings in JSON, the safest approach is to let JSON.stringify() handle escaping automatically rather than doing it manually:
// User input with special characters
const userComment = 'She said "hello" and typed C:\\Users\\docs\nThen pressed tab:\there';
// JSON.stringify handles all escaping automatically
const jsonString = JSON.stringify({ comment: userComment });
console.log(jsonString);
// {"comment":"She said \"hello\" and typed C:\\Users\\docs\nThen pressed tab:\there"}
// Parse it back — the original string is preserved exactly
const parsed = JSON.parse(jsonString);
console.log(parsed.comment === userComment); // trueThe key point: never build JSON strings by concatenation. Use your language's JSON serializer, which knows every escaping rule and applies them correctly.
Handling Multi-Line Strings
JSON does not support multi-line string literals. If you need to store text that contains line breaks, every newline must be escaped as \n:
{
"poem": "Roses are red,\nViolets are blue,\nJSON needs escaping,\nAnd so do you."
}When parsed, the poem value will contain actual newline characters, producing four lines of text. If you see a literal backslash followed by an "n" in your output, it means the string was double-escaped — a common bug we will address shortly.
Escaping Unicode Characters in API Responses
Some systems require all non-ASCII characters to be escaped as Unicode sequences for safe transport through ASCII-only channels:
import json
data = {
"greeting": "Hello, 世界!",
"emoji": "🚀",
"accented": "café"
}
# ensure_ascii=True forces all non-ASCII to \uXXXX (default behavior)
ascii_safe = json.dumps(data, ensure_ascii=True)
print(ascii_safe)
# {"greeting": "Hello, \u4e16\u754c!", "emoji": "\ud83d\ude80", "accented": "caf\u00e9"}
# ensure_ascii=False keeps Unicode characters as-is (smaller output)
utf8_output = json.dumps(data, ensure_ascii=False)
print(utf8_output)
# {"greeting": "Hello, 世界!", "emoji": "🚀", "accented": "café"}Both outputs are valid JSON. The ensure_ascii=True version is safer for systems that cannot handle UTF-8, while the ensure_ascii=False version is more readable and produces smaller files when the content contains many non-ASCII characters.
Common Mistakes with JSON Escaping
1. Double Escaping
Double escaping happens when a string is escaped twice, producing visible backslash sequences in the output instead of the intended special characters. This is the single most common escaping bug in production systems.
// The bug: stringifying an already-JSON string
const data = { message: "Line 1\nLine 2" };
const jsonStr = JSON.stringify(data);
// Correct: {"message":"Line 1\nLine 2"}
// Now imagine someone stringifies the JSON string AGAIN
const doubleEscaped = JSON.stringify(jsonStr);
// Bug: "{\"message\":\"Line 1\\nLine 2\"}"
// The consumer sees literal \n instead of a newlineThe fix: make sure you serialize your data to JSON exactly once. If you are passing data between systems, send the object and let each system handle its own serialization. If you suspect double escaping, use our JSON Stringify tool to see exactly what the escaped output looks like, or our JSON Escape tool to inspect and fix escaping issues.
2. Using Single Quotes Instead of Double Quotes
JSON requires double quotes for all string values and keys. Single quotes are a syntax error:
// INVALID JSON — single quotes
{ 'name': 'Alice' }
// VALID JSON — double quotes
{ "name": "Alice" }This is a common mistake for developers coming from Python (which allows single quotes) or JavaScript (which allows both). If you are constructing JSON manually, always use double quotes. Better yet, use a serialization library and avoid building JSON strings by hand.
3. Forgetting to Escape Backslashes in File Paths
Windows file paths contain backslashes, and each one must be escaped in JSON:
// INVALID — unescaped backslashes
{ "path": "C:\Users\Documents\file.txt" }
// VALID — escaped backslashes
{ "path": "C:\\Users\\Documents\\file.txt" }When working with file paths, always run them through JSON.stringify() or your language's equivalent. It will add the necessary backslash escapes automatically.
4. Embedding Raw HTML or XML in JSON Strings
When storing HTML content inside JSON strings, angle brackets (<, >) do not need to be escaped per the JSON specification, but double quotes and backslashes within the HTML do. Additionally, if the JSON will be embedded in an HTML <script> tag, you should escape forward slashes to prevent the browser from interpreting </script> as a closing tag.
5. Not Escaping Control Characters
Characters like tab, null bytes, and other control characters (U+0000 to U+001F) are invisible but invalid in unescaped form. JSON parsers will reject them. A common source of this error is copying text from legacy systems or databases that contain stray control characters. Use our JSON Validator to detect these hidden characters.
Best Practices for JSON Escaping
- Always use a JSON serialization library. Never construct JSON by string concatenation. Libraries like
JSON.stringify()in JavaScript,json.dumps()in Python, orJsonSerializerin C# handle every escaping rule correctly. - Validate JSON after construction. Even when using a library, validate your output — especially if you are combining JSON from multiple sources or performing string manipulations after serialization.
- Use UTF-8 encoding consistently. Save JSON files as UTF-8 without BOM. Declare
Content-Type: application/json; charset=utf-8in HTTP headers. Consistent encoding prevents garbled Unicode characters. - Be cautious with template-generated JSON. If you generate JSON inside HTML templates, shell scripts, or string interpolation, you are at high risk of escaping bugs. Parse the output through a JSON validator before shipping it.
- Test with adversarial input. Include test cases with double quotes, backslashes, newlines, Unicode characters, emoji, and null bytes. These are the characters most likely to break JSON escaping.
- Log escaped and unescaped values separately. When debugging escaping issues, print the raw bytes alongside the display string. This helps you see whether the backslash is a real character in the string or just the console's representation of a control character.
Quick Reference: JSON Escape Sequences at a Glance
Here is every escape sequence recognized by the JSON specification, summarized for easy reference:
Character Escape Sequence Unicode Code Point
───────── ─────────────── ──────────────────
" (quote) \" U+0022
\ (backslash) \\ U+005C
/ (slash) \/ U+002F (optional)
Backspace \b U+0008
Form feed \f U+000C
Newline \n U+000A
Carriage return \r U+000D
Tab \t U+0009
Any character \uXXXX U+0000 to U+FFFFTry It Now
Need to escape special characters in your JSON? Paste your string into our free JSON Escape tool to see the properly escaped output instantly. No installation required, and everything runs locally in your browser.
If you are not sure whether your JSON is valid after escaping, run it through the JSON Validator to catch any remaining issues. And if you need to convert a JavaScript object into a properly escaped JSON string, try the JSON Stringify tool.
Conclusion
JSON escaping is one of those topics that seems trivial until you get it wrong — and then it becomes a production bug. The rules themselves are straightforward: escape double quotes, backslashes, and control characters. Use \uXXXX for anything else that needs encoding. But the devil is in the details: double escaping, encoding mismatches, and manually built JSON strings are the leading sources of escaping bugs in real-world applications.
The best defense is to let your language's JSON library handle escaping, validate the output, and test with the adversarial inputs that real users will inevitably send your way. Bookmark this reference for the next time you need to look up an escape sequence or debug a "bad character" error — your future self will appreciate it.