JSON Escape

JSON escape sequences are used to represent special characters within JSON strings. Since JSON strings are enclosed in double quotes, certain characters must be escaped to avoid syntax errors.

Why Escape Characters?

  • Prevent syntax errors: Characters like quotes and backslashes can break JSON parsing
  • Represent special characters: Control characters, newlines, and Unicode symbols
  • Maintain data integrity: Ensure strings are correctly transmitted and stored

Escape Characters Table

CharacterEscape SequenceDescription
"\"Double quote
\\\Backslash
/\/Forward slash (optional)
Backspace\bBackspace character
Form feed\fForm feed character
Newline\nLine feed character
Carriage return\rCarriage return character
Tab\tHorizontal tab character
Unicode\uXXXXUnicode character (4 hex digits)

Basic Examples

Simple Text with Quotes

{
  "message": "She said \"Hello World!\"",
  "note": "This is a \"quoted\" text"
}

File Paths

{
  "windowsPath": "C:\\Users\\Documents\\file.txt",
  "networkPath": "\\\\server\\share\\folder"
}

Multi-line Text

{
  "address": "123 Main Street\nAnytown, USA\n12345",
  "poem": "Roses are red,\nViolets are blue,\nJSON is great,\nAnd so are you!"
}

Tab-separated Content

{
  "data": "Name\tAge\tCity\nJohn\t25\tNew York\nJane\t30\tLos Angeles"
}

HTML Content

{
  "htmlSnippet": "<div class=\"container\">\n  <h1>Welcome!</h1>\n  <p>This is \"quoted\" content.</p>\n</div>"
}

URLs and Special Characters

{
  "url": "https://example.com/search?q=\"json escape\"",
  "regex": "\\d{3}-\\d{2}-\\d{4}",
  "command": "echo \"Hello World\" > output.txt"
}

Unicode Characters

{
  "symbols": "Copyright: \u00A9, Trademark: \u2122",
  "emoji": "Happy: \uD83D\uDE00, Heart: \u2764\uFE0F",
  "international": "Caf\u00E9, na\u00EFve, r\u00E9sum\u00E9"
}

Common Mistakes

❌ Wrong - Unescaped quotes

{
  "error": "She said "Hello" to me"
}

✅ Correct - Escaped quotes

{
  "correct": "She said \"Hello\" to me"
}

❌ Wrong - Raw newlines

{
  "error": "Line 1
Line 2"
}

✅ Correct - Escaped newlines

{
  "correct": "Line 1\nLine 2"
}

❌ Wrong - Single backslash in paths

{
  "error": "C:\Users\Documents"
}

✅ Correct - Escaped backslashes

{
  "correct": "C:\\Users\\Documents"
}

Quick Reference

Most Common Escapes

  • \" for quotes inside strings
  • \\ for backslashes (especially in file paths)
  • \n for new lines
  • \t for tabs

When to Escape

  • Always escape double quotes inside JSON strings
  • Always escape backslashes
  • Use \n instead of actual line breaks
  • Use \t for consistent tab spacing

Testing Your JSON

Use online JSON validators to check if your escaped JSON is valid:

  • Copy and paste your JSON into a validator
  • Look for syntax error messages
  • Fix any unescaped characters

Remember: Most programming languages have built-in functions to automatically handle JSON escaping, so you don't need to escape manually in most cases!