Escaping Special Characters in JSON and YAML

Learn how to handle special characters when converting between JSON and YAML. Covers quoting rules, escape sequences, and characters that require special treatment.

Strings

Detailed Explanation

Special characters require different escaping strategies in JSON and YAML. Understanding these differences is crucial for lossless conversion between the two formats.

JSON escaping rules: JSON uses backslash escape sequences within double-quoted strings:

{
  "path": "C:\\Users\\admin",
  "message": "She said \\"hello\\"",
  "newline": "line1\nline2",
  "tab": "col1\tcol2",
  "unicode": "\u00e9"
}

The same data in YAML (unquoted where possible):

path: C:\Users\admin
message: 'She said "hello"'
newline: "line1\nline2"
tab: "col1\tcol2"
unicode: "\u00e9"

YAML quoting styles:

  1. No quotes -- Works for most simple strings. Cannot contain : # [ ] { } , & * ? | - < > = ! % @ \\ at the start.
  2. Single quotes ('') -- No escape sequences are processed. Only escape is '' for a literal single quote. Best for strings with backslashes or double quotes.
  3. Double quotes ("") -- Supports escape sequences like \n, \t, \\, \". Closest to JSON behavior.

Characters that force quoting in YAML:

# These must be quoted:
colon_value: "value: with colon"
hash_value: "value # with hash"
bracket: "[not an array]"
ampersand: "&not_an_anchor"
asterisk: "*not_an_alias"
at_start_dash: "- not a list item"

When converting JSON to YAML, a good converter will:

  • Remove quotes from simple strings ("hello" becomes hello)
  • Keep double quotes for strings with escape sequences
  • Use single quotes for strings containing double quotes
  • Use block scalars for multiline strings

When converting YAML to JSON, all values become double-quoted strings with proper JSON escape sequences. This is always a safe transformation since JSON has a single unambiguous string format.

Use Case

Converting a JSON file containing file system paths, regex patterns, or template strings with special characters to YAML while preserving the exact string values.

Try It — JSON ↔ YAML Converter

Open full tool