How to Escape a String for JSON
To embed arbitrary text inside a JSON string you must escape a specific set of characters. Here is the full list, what each sequence means, and the safe way to generate it.
What must be escaped
Inside a JSON string only a handful of characters need a backslash escape: the double quote \", the backslash itself \\, and the control characters — newline \n, carriage return \r, tab \t, backspace \b, and form feed \f. Any other control character (code point below U+0020) must be written as a \u00XX escape. Everything else, including ordinary letters and most Unicode, can stay as-is.
A worked example
This raw text (a quote, a newline, a tab, and a Windows path):
He said "hi"
path: C:\tempbecomes this valid JSON string value:
"He said \"hi\"\n\tpath: C:\\temp"Notice the three transformations: each " became \", the real newline and tab became \n and \t, and the single backslash in C:\temp became \\.
The escape that people forget
The forward slash / may be escaped as \/ but does not have to be — both are valid. The one that bites people is the lone backslash: Windows paths and regex patterns are full of them, and a single \ that is not part of a valid escape sequence makes the whole document invalid.
Do it programmatically, not by hand
Hand-escaping is error-prone. In every major language the standard JSON serializer does it correctly: JSON.stringify(text) in JavaScript, json.dumps(text) in Python. Pass your raw string to one of those and it returns the fully-escaped, quote-wrapped JSON string.
FAQ
Which characters have to be escaped in a JSON string?
The double quote, the backslash, and the control characters newline, carriage return, tab, backspace and form feed. Other control characters below U+0020 use \u00XX escapes.
Do I need to escape the forward slash?
No. \/ is allowed but optional; a bare / is perfectly valid inside a JSON string.
What is the safest way to escape a string for JSON?
Use your language's JSON serializer — JSON.stringify in JavaScript or json.dumps in Python — rather than replacing characters by hand. It handles every required escape correctly.