JSON Escaping and Encoding

Escape sequences, Unicode, URLs, embedded JSON strings, and encoding pitfalls when storing or transporting JSON.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Escaping basics
Escape a backslash
{
  "path": "C:\\Users\\Ada\\file.txt"
}

# Represent a literal backslash inside a string.

Escape a forward slash if needed
{
  "html": "<\/script>"
}

# Escaping `/` is optional in JSON.

Escape control characters
{
  "log": "first line
second line\r
third line"
}

# Use `\n`, `\r`, and `\t` for control characters.

## Encoding pitfalls
Prefer UTF-8 encoded JSON
Content-Type: application/json; charset=utf-8

# UTF-8 is the de facto standard for JSON payloads.

JSON string containing JSON
{
  "payload": "{\"event\":\"signup\",\"ok\":true}"
}

# Sometimes one field stores another JSON document as a string.

Decode embedded JSON with jq
jq '.payload | fromjson' event.json

# Parse a JSON string field into structured data.

Encode structured data as a JSON string
jq -n '{event:"signup",ok:true} | @json'

# Turn a value into a JSON-encoded string.

Recommended next

No recommendations yet.