How to Escape and Unescape JSON Strings
JSON uses a specific set of escape sequences to include special characters within strings. If your string contains a double quote, a backslash, or control characters, you must escape them for the JSON to be valid. Understanding JSON escaping is essential for generating correct JSON output and debugging malformed JSON payloads.
JSON Escape Sequences
| Character | Escape Sequence | Description |
|---|---|---|
" |
\" |
Double quote |
\ |
\\ |
Backslash |
/ |
\/ |
Forward slash |
\b |
\\b |
Backspace |
\f |
\\f |
Form feed |
\n |
\\n |
Newline |
\r |
\\r |
Carriage return |
\t |
\\t |
Tab |
\uXXXX |
\\uXXXX |
Unicode character by hex code |
When Escaping Is Needed
If you embed a user-generated string in a JSON payload, you must escape it. Consider a JSON object where a name field contains a double quote:
{"name": "John "The Man" Doe"}
This JSON is invalid because the double quotes inside the value terminate the string prematurely. The correct output is:
{"name": "John \"The Man\" Doe"}
Language-Specific Methods
JavaScript
JavaScript provides JSON.stringify() which automatically escapes strings.
const user = { name: 'John "The Man" Doe' };
const json = JSON.stringify(user);
console.log(json);
// Output: {"name":"John \"The Man\" Doe"}
// Manual escape (rarely needed)
function escapeJson(str) {
return str
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/\f/g, '\\f');
}
// Unescape
function unescapeJson(str) {
return JSON.parse(`"${str}"`);
}
PHP
// Automatic via json_encode
$data = ['name' => 'John "The Man" Doe'];
echo json_encode($data);
// Output: {"name":"John \"The Man\" Doe"}
// Manual escape
$escaped = addslashes('John "The Man" Doe');
echo $escaped;
// Output: John \"The Man\" Doe
// JSON_UNESCAPED_UNICODE flag preserves Unicode
echo json_encode(['emoji' => '😀'], JSON_UNESCAPED_UNICODE);
// Output: {"emoji":"😀"}
Python
import json
# Automatic via json.dumps
data = {"name": 'John "The Man" Doe'}
print(json.dumps(data))
# Output: {"name": "John \"The Man\" Doe"}
# Pretty print with escape
print(json.dumps(data, indent=2))
# Ensure ASCII flag escapes Unicode
print(json.dumps({"emoji": "😀"}, ensure_ascii=True))
# Output: {"emoji": "\ud83d\ude00"}
Ruby
require 'json'
data = { name: 'John "The Man" Doe' }
puts JSON.generate(data)
# Output: {"name":"John \"The Man\" Doe"}
# Or with pretty formatting
puts JSON.pretty_generate(data)
Common Mistakes
Double escaping happens when you escape an already-escaped string. The sequence \\" becomes \\\\\\" if escaped again, and the JSON becomes corrupted.
Missing Unicode escapes for non-ASCII characters. While JSON supports Unicode directly in UTF-8 environments, some old parsers expect \uXXXX sequences. The ensure_ascii flag in Python controls this behaviour.
Not escaping control characters. A raw newline character inside a JSON string is invalid. Always use \n instead.
Online Tool
The JSON Escape & Unescape tool on Help2Code provides instant escaping and unescaping. Paste your string, choose the direction, and copy the result. It is the fastest way to escape a string for inclusion in a JSON payload.
Escaping in Nested Contexts
When JSON is embedded in another format like HTML or a URL, you need multiple layers of escaping. A JSON string inside an HTML attribute value must be JSON-escaped and then HTML-entity-encoded:
<div data-config='{"name":"John "The Man" Doe"}'>
The JSON uses \" for the quotes, then the HTML attribute uses " for the JSON string. Both layers are necessary to produce valid output.
Conclusion
Proper JSON escaping ensures your data serialises correctly and your JSON parsers do not choke on special characters. Use your language's built-in JSON serialisation functions rather than manual escaping for production code. For quick escaping tasks, the JSON Escape & Unescape online tool is the fastest option.