Skip to content
Back to Learn
·5 min read

JSON Escape and Unescape Guide: Handling Special Characters

JSON escape and unescape operations handle special characters within JSON strings. Every JSON string must escape certain characters — double quotes, backslashes, control characters — and may use Unicode escape sequences for non-ASCII characters. Understanding these rules is essential for generating valid JSON programmatically and for debugging escape-related issues. Use our JSON Escape/Unescape tool to handle special characters and JSON Validator to verify outputs.

JSON Escape Sequences Reference

Escape SequenceRepresentsUnicode Code Point
\"Double quoteU+0022
\\BackslashU+005C
\/Forward slashU+002F
\bBackspaceU+0008
\fForm feedU+000C
\nNewlineU+000A
\rCarriage returnU+000D
\tTabU+0009
\uXXXXUnicode characterU+XXXX (4 hex digits)

Why Escape JSON?

JSON strings are delimited by double quotes. To include a literal double quote inside a string, it must be escaped with a backslash. Similarly, backslashes themselves must be escaped. Control characters (codes below U+0020) must also be escaped, typically as Unicode escapes.

// Valid JSON strings with escapes
"He said, \"Hello!\""
"C:\\Users\\Alice"
"Line 1\nLine 2"
"Tab\there"
"Emoji: \uD83D\uDE80"

// These would be INVALID:
'He said, "Hello!"'  // Single quotes not allowed
"He said, "Hello!""   // Double quotes inside double quotes
"He said, \u000A"    // Newline inside string (must be \n)

Escaping in Different Languages

JavaScript

// String with special characters
const str = 'He said "Hello" in "C:\Files"';
const escaped = JSON.stringify(str);
// '"He said \"Hello\" in \"C:\\Files\""'

// The reverse
const original = JSON.parse(escaped);

// Custom escaping function
function escapeJSON(str) {
  return str.replace(/[\"\n\r\t\b\f]/g, (char) => {
    const map = {
      '\\': '\\\\',
      '"': '\\"',
      '\n': '\\n',
      '\r': '\\r',
      '\t': '\\t',
      '\b': '\\b',
      '\f': '\\f'
    };
    return map[char];
  });
}

// Unescape
function unescapeJSON(str) {
  return str.replace(/\\([\\"nrtbf])/g, (_, char) => {
    const map = {
      '\\': '\\',
      '"': '"',
      'n': '\n',
      'r': '\r',
      't': '\t',
      'b': '\b',
      'f': '\f'
    };
    return map[char];
  });
}

Python

import json

# Escaping
data = {'message': 'He said "Hello" in C:\Files'}
escaped = json.dumps(data)
# '{"message": "He said \"Hello\" in C:\\Files"}'

# Unescaping
original = json.loads(escaped)

# Manual escape
escaped_str = json.dumps("Hello\nWorld")
# '"Hello\\nWorld"'

# With ensure_ascii=False for non-ASCII
json.dumps("Café", ensure_ascii=False)  # '"Café"'
json.dumps("Café", ensure_ascii=True)   # '"Caf\u00e9"'

Java

import org.apache.commons.text.StringEscapeUtils;

// Escape JSON string
String escaped = StringEscapeUtils.escapeJson("He said "Hello"");
// "He said \"Hello\""

// Unescape
String unescaped = StringEscapeUtils.unescapeJson(escaped);

// Using Jackson
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString("He said "Hello"");
// ""He said \"Hello\"""

Common JSON Escape Issues

IssueExampleFix
Unescaped double quotes{"key": "value "with" quotes"}Use \" instead: {"key": "value \"with\" quotes"}
Unescaped backslashes{"path": "C:\Users"}Use \\: {"path": "C:\\Users"}
Literal newlines in stringsString spans multiple linesUse \n escape
Invalid Unicode escapes\uXYZ (wrong length)Must be exactly 4 hex digits
Lone surrogates\uD800 without pairMust form valid surrogate pair
Control charactersTab, null, etc. unescapedUse \t, \u0000, etc.

Escape for Different Contexts

// JSON inside HTML
// If embedding JSON in HTML attributes or script tags:
var jsonStr = JSON.stringify(largeObject)
  .replace(/<\/script>/gi, '<\\/script>')
  .replace(/<!--/g, '<\\!--');
var html = '<script>var data = ' + jsonStr + ';</script>';

// JSON inside URL parameters
var encoded = encodeURIComponent(JSON.stringify(filterObject));
var url = 'https://api.example.com?data=' + encoded;

// JSON inside single-quoted strings
const jsonString = JSON.stringify(obj).replace(/\\/g, '\\\\');
// Use /json-escape-unescape to handle these cases

Using Our JSON Escape/Unescape Tool

Our JSON Escape/Unescape tool supports three modes:

  • Escape — Convert plain text to JSON-escaped string (adds outer quotes, escapes special chars)
  • Unescape — Convert JSON-escaped string back to plain text
  • Toggle — Detect and convert between escaped and unescaped

Use our JSON Validator to check that escaped JSON strings are valid before using them in production.

Best Practices

  • Always use JSON.stringify() (or language equivalent) rather than manual string building
  • Never concatenate strings to build JSON — this inevitably creates escape issues
  • Use proper encoding for the target context (HTML, URL, database)
  • Validate all generated JSON with JSON Validator
  • Use our JSON Escape/Unescape for debugging and quick conversions
  • For user-generated content, escape all special characters before inserting into JSON

Next Steps

Escape or unescape JSON strings with JSON Escape/Unescape. Validate outputs with JSON Validator. Format escaped JSON with JSON Formatter.