JSON Escape and Unescape Guide: Handling Special Characters
JSON escape and unescape operations handle special characters within JSON strings. Every JSON string must escape certain characters — double quotes, backslashes, control characters — and may use Unicode escape sequences for non-ASCII characters. Understanding these rules is essential for generating valid JSON programmatically and for debugging escape-related issues. Use our JSON Escape/Unescape tool to handle special characters and JSON Validator to verify outputs.
JSON Escape Sequences Reference
| Escape Sequence | Represents | Unicode Code Point |
|---|---|---|
\" | Double quote | U+0022 |
\\ | Backslash | U+005C |
\/ | Forward slash | U+002F |
\b | Backspace | U+0008 |
\f | Form feed | U+000C |
\n | Newline | U+000A |
\r | Carriage return | U+000D |
\t | Tab | U+0009 |
\uXXXX | Unicode character | U+XXXX (4 hex digits) |
Why Escape JSON?
JSON strings are delimited by double quotes. To include a literal double quote inside a string, it must be escaped with a backslash. Similarly, backslashes themselves must be escaped. Control characters (codes below U+0020) must also be escaped, typically as Unicode escapes.
// Valid JSON strings with escapes
"He said, \"Hello!\""
"C:\\Users\\Alice"
"Line 1\nLine 2"
"Tab\there"
"Emoji: \uD83D\uDE80"
// These would be INVALID:
'He said, "Hello!"' // Single quotes not allowed
"He said, "Hello!"" // Double quotes inside double quotes
"He said, \u000A" // Newline inside string (must be \n)
Escaping in Different Languages
JavaScript
// String with special characters
const str = 'He said "Hello" in "C:\Files"';
const escaped = JSON.stringify(str);
// '"He said \"Hello\" in \"C:\\Files\""'
// The reverse
const original = JSON.parse(escaped);
// Custom escaping function
function escapeJSON(str) {
return str.replace(/[\"\n\r\t\b\f]/g, (char) => {
const map = {
'\\': '\\\\',
'"': '\\"',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
'\b': '\\b',
'\f': '\\f'
};
return map[char];
});
}
// Unescape
function unescapeJSON(str) {
return str.replace(/\\([\\"nrtbf])/g, (_, char) => {
const map = {
'\\': '\\',
'"': '"',
'n': '\n',
'r': '\r',
't': '\t',
'b': '\b',
'f': '\f'
};
return map[char];
});
}
Python
import json
# Escaping
data = {'message': 'He said "Hello" in C:\Files'}
escaped = json.dumps(data)
# '{"message": "He said \"Hello\" in C:\\Files"}'
# Unescaping
original = json.loads(escaped)
# Manual escape
escaped_str = json.dumps("Hello\nWorld")
# '"Hello\\nWorld"'
# With ensure_ascii=False for non-ASCII
json.dumps("Café", ensure_ascii=False) # '"Café"'
json.dumps("Café", ensure_ascii=True) # '"Caf\u00e9"'
Java
import org.apache.commons.text.StringEscapeUtils;
// Escape JSON string
String escaped = StringEscapeUtils.escapeJson("He said "Hello"");
// "He said \"Hello\""
// Unescape
String unescaped = StringEscapeUtils.unescapeJson(escaped);
// Using Jackson
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString("He said "Hello"");
// ""He said \"Hello\"""
Common JSON Escape Issues
| Issue | Example | Fix |
|---|---|---|
| Unescaped double quotes | {"key": "value "with" quotes"} | Use \" instead: {"key": "value \"with\" quotes"} |
| Unescaped backslashes | {"path": "C:\Users"} | Use \\: {"path": "C:\\Users"} |
| Literal newlines in strings | String spans multiple lines | Use \n escape |
| Invalid Unicode escapes | \uXYZ (wrong length) | Must be exactly 4 hex digits |
| Lone surrogates | \uD800 without pair | Must form valid surrogate pair |
| Control characters | Tab, null, etc. unescaped | Use \t, \u0000, etc. |
Escape for Different Contexts
// JSON inside HTML
// If embedding JSON in HTML attributes or script tags:
var jsonStr = JSON.stringify(largeObject)
.replace(/<\/script>/gi, '<\\/script>')
.replace(/<!--/g, '<\\!--');
var html = '<script>var data = ' + jsonStr + ';</script>';
// JSON inside URL parameters
var encoded = encodeURIComponent(JSON.stringify(filterObject));
var url = 'https://api.example.com?data=' + encoded;
// JSON inside single-quoted strings
const jsonString = JSON.stringify(obj).replace(/\\/g, '\\\\');
// Use /json-escape-unescape to handle these cases
Using Our JSON Escape/Unescape Tool
Our JSON Escape/Unescape tool supports three modes:
- Escape — Convert plain text to JSON-escaped string (adds outer quotes, escapes special chars)
- Unescape — Convert JSON-escaped string back to plain text
- Toggle — Detect and convert between escaped and unescaped
Use our JSON Validator to check that escaped JSON strings are valid before using them in production.
Best Practices
- Always use
JSON.stringify()(or language equivalent) rather than manual string building - Never concatenate strings to build JSON — this inevitably creates escape issues
- Use proper encoding for the target context (HTML, URL, database)
- Validate all generated JSON with JSON Validator
- Use our JSON Escape/Unescape for debugging and quick conversions
- For user-generated content, escape all special characters before inserting into JSON
Next Steps
Escape or unescape JSON strings with JSON Escape/Unescape. Validate outputs with JSON Validator. Format escaped JSON with JSON Formatter.