To unescape a JSON string, parse it with a JSON parser instead of removing backslashes by hand. In JavaScript that is JSON.parse, in Python json.loads, and on the command line jq's fromjson. If the text was stringified twice, the first parse returns another string, so you parse it a second time.
What unescaping a JSON string actually means
Unescaping a JSON string means turning escape sequences back into the characters they represent. The JSON standard, RFC 8259, defines a short list of two-character escapes:
| Escape | Character |
|---|---|
\" |
quotation mark |
\\ |
backslash (reverse solidus) |
\/ |
forward slash (solidus) |
\b |
backspace |
\f |
form feed |
\n |
line feed |
\r |
carriage return |
\t |
tab |
Any character can also be written as \u followed by four hex digits. Characters outside the Basic Multilingual Plane take two of those, a surrogate pair: the G clef, U+1D11E, is written "\uD834\uDD1E".
A hand-written replace has to get every one of these right, including a \\ that sits right before an n.
Unescape a JSON string in JavaScript with JSON.parse
JSON.parse unescapes a JSON string as part of parsing it. Per the JSON.parse reference, it returns the object, array, string, number, boolean or null that the text describes, and it throws a SyntaxError when the text isn't valid JSON.
const raw = '"She said \\"hi\\"\\nthen left"';
const text = JSON.parse(raw);
console.log(text);
// She said "hi"
// then left
The outer quotes inside raw are required. JSON.parse only accepts a complete JSON value, and a JSON string value starts and ends with a double quote.
Skip the old global unescape() function. It is deprecated and only decodes %XX and %uXXXX sequences, so it leaves \n and \" exactly as they were.
Unescape a JSON string in Python with json.loads
Python's json.loads does the same job. It takes a str, bytes or bytearray that holds a JSON document, and a JSON string comes back as a Python str with the escapes resolved.
import json
raw = r'"C:\\temp\\logs\nnext line"'
print(json.loads(raw))
# C:\temp\logs
# next line
The r prefix matters. Without it, Python processes the backslashes in your source code before json.loads ever sees them, and you end up debugging the wrong layer. If the input isn't valid JSON, you get json.JSONDecodeError, a subclass of ValueError with lineno and colno attributes that point at the problem.
Unescape JSON on the command line with jq
jq unescapes a JSON string in two ways, depending on what you want out. To print a string value as plain text, use -r: the jq manual says raw output writes a string directly instead of formatting it as a quoted JSON string.
echo '{"msg":"line one\nline two"}' | jq -r '.msg'
When a field holds a whole JSON document as a string, pipe it through fromjson. Without it, jq treats the value as text, and a path like .payload.id fails with Cannot index string with string.
echo '{"payload":"{\"id\":7,\"ok\":true}"}' | jq '.payload | fromjson | .id'
tojson goes the other way and turns a value back into escaped JSON text. For more jq output options, see pretty print JSON with jq.
Which fix fits your input?
The right unescape step depends on the shape of the text you have. The search results I read mostly show the one-liner and skip this part. Match your input to a row:
| What you have | Example | What to do |
|---|---|---|
| A full JSON string literal | "a\"b\nc" |
Parse once |
| A bare fragment, no outer quotes | a\"b\nc |
Wrap in " and ", then parse |
| A stringified object | "{\"id\":1}" |
Parse twice |
| An object with one stringified field | {"payload":"{\"id\":1}"} |
Parse the object, then parse that field |
The bare fragment is the case that trips people up. You copy Line one\nLine two out of a log, call JSON.parse on it, and get a SyntaxError, because a fragment without quotes isn't a JSON value. Wrap it first:
const fragment = 'Line one\\nLine two';
const text = JSON.parse('"' + fragment + '"');
This works only if the fragment's own quotes are already escaped as \". A raw " in the middle ends the string early and the parse fails. That failure is useful: the text was never valid escaped JSON.
Double-escaped JSON: parse it twice
Double-escaped JSON is JSON text that was encoded as a string, then encoded again. It usually comes from calling JSON.stringify or json.dumps on data that was already a JSON string, and the lasting fix is to encode once at the source. The full story of that bug is in JSON.stringify vs JSON.parse.
When you can't fix the producer, parse until you get something that isn't a string. Cap the loop so a plain text value can't spin forever:
import json
def unescape_json(text, max_depth=5):
value = json.loads(text)
depth = 1
while isinstance(value, str) and depth < max_depth:
try:
value = json.loads(value)
except json.JSONDecodeError:
break
depth += 1
return value
My take: use the loop only for inspecting logs and third-party payloads. In your own code, a value that needs an unknown number of parses is a bug. Fix it where the value is written.
Common mistakes when unescaping JSON
Broken unescape code usually makes one of these mistakes:
- Regex replacement. Stripping every backslash turns
\\(one real backslash) into nothing and leaves\ucodes as gibberish. - Forgetting the outer quotes. A bare fragment throws
SyntaxErrorin JavaScript andJSONDecodeErrorin Python. - Escaping at the wrong layer. In Python source and JavaScript string literals, the language consumes one level of backslashes before the JSON parser runs. Raw strings in Python avoid that.
- Unescaping, then writing the result back as JSON by hand. If you need JSON again, re-serialize with
JSON.stringifyorjson.dumpsso the escapes are rebuilt correctly. The rules for that side are in how to escape double quotes in JSON.
If a parse fails with an error at the very first character, the guide to unexpected token at position 0 covers the usual causes.
Unescape JSON without writing code
For a one-off cleanup, a browser tool is faster than a script. OnlineViewer's JSON unescape tool cleans double-escaped and stringified JSON. The tool code runs in the page and makes no network requests, which matters when the payload holds tokens or customer data.
The limitation: the tool assumes the input is escaped JSON and nothing else. If your text mixes JSON escapes with other encodings, such as percent-encoding from a URL, you have to undo each layer in the right order yourself.
FAQ
What is the easiest way to unescape a JSON string?
Run it through a JSON parser. JSON.parse in JavaScript, json.loads in Python and fromjson in jq all turn sequences like " and \n back into the characters they stand for.
Why does JSON.parse give me a string instead of an object?
The JSON was stringified twice. The first parse removes one layer and returns the inner JSON text as a string. Parse that string again to get the object.
Can I use JavaScript's unescape() function on JSON?
No. unescape() is deprecated and only decodes percent sequences such as %XX and %uXXXX. It leaves JSON backslash escapes like \n and " untouched.
How do I unescape a fragment that has no quotes around it?
Wrap it in double quotes first, then parse it. A bare fragment like Line one\nLine two is not valid JSON on its own, but "Line one\nLine two" is a valid JSON string.
Is replacing backslashes with a regex safe?
Usually not. A regex that strips backslashes breaks \ (a real backslash), \uXXXX escapes and surrogate pairs. A JSON parser handles every escape the standard defines.