Unescape a JSON string in C#
// json is the escaped string with its quotes: "{\"id\":1}"
string? text = JsonSerializer.Deserialize<string>(json); // {"id":1}
// Only the inside, without the quotes? Add them first.
string? text2 = JsonSerializer.Deserialize<string>($"\"{inside}\"");
// Double-serialized JSON: read the string, then parse it.
JsonNode? node = JsonNode.Parse(text!);
Input without the surrounding quotes is read here the second way, as the inside of a JSON string. The literal null (with no quotes) deserializes to a null string. Anything else that is not a JSON string, such as a number or an object, fails with The JSON value could not be converted to System.String.
Why JSON ends up escaped
The usual cause is serializing twice: JSON that is already a string gets serialized again. Typical cases are Results.Json(json) or JsonSerializer.Serialize(json) called on a string that already holds JSON, and a DTO with a string property that holds a JSON document. The client then receives a JSON string that contains JSON: "{\"id\":1}". Pass the object itself, or a JsonNode / JsonElement for JSON you only have as text, and it is serialized once. Logs do the same when a JSON payload is written as a property of a JSON log entry.
Errors
- An invalid escape, such as
\xor\': JSON only allows\",\\,\/,\b,\f,\n,\r,\tand\uwith four hex digits. - A raw line break or tab inside the string: control characters must be escaped.
- A lone surrogate, such as
\uD800with no\uDC00after it: the serializer cannot turn it into a .NET string and reports that the value could not be converted.
The message and LineNumber / BytePositionInLine (both counted from 0) are what .NET reports. Click the message to jump to the spot.
FAQ
Why is my JSON full of backslashes?
It was serialized twice: a JSON document was stored in a string and that string was serialized again, so every quote became \". Deserialize it to a string first, then parse that string as JSON, or better, stop serializing it twice by serializing the object, or a JsonNode, instead of a JSON string.
How do I unescape a JSON string in C#?
JsonSerializer.Deserialize<string>(json) returns the text. The input must include the surrounding quotes; if you only have the inside, add them first.
What is the difference between \/ and /?
None: JSON allows the forward slash to be escaped, and both read back as /. System.Text.Json never escapes it when writing.
Can I unescape a C# string literal here?
Mostly: the escapes \", \\, \n, \r, \t and \uXXXX are the same. C#-only escapes such as \x41, \0 and \a are not valid JSON and are reported.
Is my text uploaded?
No. The unescaping happens in your browser, not on a server.