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

The escape sequences you use most often in JSON strings.

Escape a backslash

Represent a literal backslash inside a string.

jsonANYjsonescapingbackslash
json
{
  "path": "C:\\Users\\Ada\\file.txt"
}

Backslashes must be escaped inside JSON strings.

Escape a forward slash if needed

Escaping `/` is optional in JSON.

jsonANYjsonescapingslash
json
{
  "html": "<\/script>"
}

Some serializers escape `/` defensively in HTML contexts.

Escape control characters

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

jsonANYjsonescapingcontrol-characters
json
{
  "log": "first line
second line\r
third line"
}

Control characters must be escaped when they appear inside a JSON string.

Encoding pitfalls

Common mistakes when JSON crosses system boundaries.

Prefer UTF-8 encoded JSON

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

textANYjsonutf8encoding
text
Content-Type: application/json; charset=utf-8

Most modern APIs and parsers assume UTF-8.

JSON string containing JSON

Sometimes one field stores another JSON document as a string.

jsonANYjsonescapingnested-json
json
{
  "payload": "{\"event\":\"signup\",\"ok\":true}"
}

This is valid, but consumers must decode the outer JSON and then parse the inner string separately.

Decode embedded JSON with jq

Parse a JSON string field into structured data.

bashANYjsonjqfromjson
bash
jq '.payload | fromjson' event.json

Useful when a system stores JSON inside a string field.

Encode structured data as a JSON string

Turn a value into a JSON-encoded string.

bashANYjsonjqtojson
bash
jq -n '{event:"signup",ok:true} | @json'

Helpful when generating escaped JSON for embedding in another payload.

Recommended next

No recommendations yet.