jsonescapingstringsdebugging

JSON Escape and Unescape: What It Is and When You Need It

·8 min read

What Is JSON Escaping?

JSON escaping converts a raw JSON string into a form that can be safely embedded inside another JSON string value, a Java/C# string literal, a SQL query, an HTML attribute, or a URL parameter. It is the process of adding backslash sequences so that a JSON parser or string parser does not misinterpret special characters.

Think of it as quoting inside a quote — you must mark the inner quotes so the outer parser does not treat them as the end of the string.

Escaping converts this:

json
{"name": "Ravi Kumar", "city": "Surat"}

to this (safe to embed as a string value):

"{"name": "Ravi Kumar", "city": "Surat"}"

Unescaping reverses the process — converts an escaped string back to readable JSON.

Characters That Must Be Escaped in JSON Strings

Per RFC 8259, these characters must be escaped when appearing inside a JSON string value:

CharacterEscape sequenceUnicodeWhy
"\"U+0022Terminates the string in JSON
\\\U+005CEscape character itself
/\/U+002FOptional — only for </ in HTML contexts
Backspace\bU+0008Control character
Form feed\fU+000CControl character
Newline\nU+000AControl character
Carriage return\rU+000DControl character
Tab\tU+0009Control character
Any Unicode code point < U+0020\uXXXXAll control characters

When Do You Need to Escape JSON?

1. Nesting JSON as a string value inside another JSON object

Some APIs accept a pre-serialized JSON document as a string field:

json
{
  "action": "process",
  "metadata": { "version": 2 },
  "payload": "{"id": 1, "event": "purchase", "amount": 99.99}"
}

The payload field contains JSON as a string — every " inside it must be escaped as \".

2. Embedding JSON in SQL INSERT statements

sql
-- DANGEROUS — never do this with user input (SQL injection risk)
INSERT INTO events (payload) VALUES ('{"event": "login", "user": "ravi"}');

-- SAFE — use parameterized queries
INSERT INTO events (payload) VALUES ($1);  -- pass JSON as a parameter

Always use parameterized queries. Never interpolate JSON directly into SQL strings.

3. Embedding JSON in Java or C# string literals

java
// Java — double quotes inside the string must be escaped with backslash
String json = "{\"name\": \"Ravi\", \"age\": 28}";

// Java 15+ Text Blocks — no escaping needed
String json = """
    {"name": "Ravi", "age": 28}
    """;
csharp
// C# — verbatim string with @: double quotes doubled
string json = @"{""name"": ""Ravi"", ""age"": 28}";

4. Embedding JSON in HTML attributes or `<script>` tags

html
<!-- For data attributes, escape both JSON and HTML -->
<div data-config='{"theme":"dark","lang":"en"}'></div>

<!-- In script tags — avoid </script> appearing in JSON strings -->
<script>
  const config = {"apiUrl": "https://api.example.com"};
  // If a JSON string value contained </script>, it would break the page
</script>

5. JSON in URLs (query parameters)

When sending JSON as a URL query parameter, you need both JSON escaping AND URL percent-encoding:

javascript
const filter = { status: "active", minScore: 90 };
const encoded = encodeURIComponent(JSON.stringify(filter));
const url = `/api/users?filter=${encoded}`;
// /api/users?filter=%7B%22status%22%3A%22active%22%2C%22minScore%22%3A90%7D

JSON.stringify Escapes Automatically

In JavaScript, JSON.stringify() is the standard way to escape a JSON string:

javascript
const raw = '{"name": "Ravi", "city": "Surat"}';

// Escape: stringify the string (not the object)
const escaped = JSON.stringify(raw);
console.log(escaped);
// → '"{"name": "Ravi", "city": "Surat"}"'
// The output is a JSON string value (wrapped in quotes) with inner quotes escaped

// Unescape: parse the escaped string
const unescaped = JSON.parse(escaped);
console.log(unescaped);
// → '{"name": "Ravi", "city": "Surat"}'  (original string restored)

Unescaping in Different Languages

JavaScript:

javascript
const escaped = '"{\"name\": \"Ravi\"}"';
const unescaped = JSON.parse(escaped);
// → '{"name": "Ravi"}'

Python:

python
import json
escaped = '"{\"name\": \"Ravi\"}"'
unescaped = json.loads(escaped)
# → '{"name": "Ravi"}'

Go:

go
var unescaped string
json.Unmarshal([]byte(`"{\"name\": \"Ravi\"}"`), &unescaped)
// unescaped = '{"name": "Ravi"}'

Common Mistakes and Gotchas

Double escaping: If you escape JSON that is already escaped, you get \\" instead of \" — the string looks garbled. Unescape once to get back to the original. Check by counting backslash pairs.

Single quotes: JSON strings always use double quotes. Single-quote escaping (\') is not JSON escaping — it is shell escaping or SQL escaping.

HTML entities: &amp;, &quot;, and &#39; are HTML encoding, not JSON escaping. If you see these in JSON, your HTML was HTML-encoded before being embedded in JSON. Use an HTML decoder, then a JSON decoder.

Newlines in JSON strings: A literal newline inside a JSON string value is invalid. Replace actual newline characters with \n before embedding.

javascript
// Wrong — literal newline in JSON string
const bad = '{"message": "Hello
World"}';

// Correct — escaped newline
const good = '{"message": "Hello\nWorld"}';

Quick Reference: Escape vs Unescape Decision

SituationWhat to do
Sending JSON to an APIUse JSON.stringify(object) — no manual escaping needed
Storing JSON as a string in another JSONJSON.stringify(JSON.stringify(object))
Reading escaped JSON you receivedJSON.parse(JSON.parse(escaped))
Debugging a garbled stringUnescape once and see if it becomes readable JSON
JSON in SQLUse parameterized queries — never string interpolation

Use JSONKit's JSON Escape/Unescape tool to escape or unescape any JSON string in one click — handles all special characters automatically.

Try JSON Escape / Unescape

Escape JSON into a safe string literal or unescape it back to readable JSON.