JSON · 12 min read

JSON Pointer Escapes: Decoding Error Locations Without Breaking Paths

API validation errors hand you a pointer string, not a path. Decode it correctly or you will search one level below the actual data.

Diagram of a JSON Pointer string with tilde escape sequences being decoded into a path through a JSON document tree

When a validation layer rejects a JSON payload, the useful part of the response is rarely the message. It is the location. Modern APIs — especially those that speak the problem details format from RFC 9457 — attach a JSON Pointer to each error, a short string that names the exact node at fault: /users/1/address~1street. If you treat that string as a plain path and split it on slashes, you will end up looking for a key named address~1street that does not exist, while the real key — address/street — sits exactly where you stopped searching.

That tilde in the middle is not decoration. It is an escape sequence, and JSON Pointer has exactly two of them. The mechanism is small enough to fit in a paragraph, which is probably why so many implementations get it wrong: the decode order is easy to flip, the empty-string key is easy to miss, and the difference between a pointer and a URL fragment is easy to blur. This guide covers the whole picture — what a pointer is under RFC 6901, why the escapes exist, the decode order that trips people up, and a practical workflow for turning any error pointer into a resolved path in the document you actually have.

What a JSON Pointer actually is

RFC 6901 defines a JSON Pointer as a string syntax for identifying one specific value inside a JSON document. It is worth being precise about what that means, because the term gets stretched in casual usage. A pointer is not a query language, not XPath, and not a URL. It is a minimal addressing scheme built from reference tokens separated by forward slashes. A pointer that starts with / walks from the document root: each token after a slash names exactly one step down, either an object property name or an array index.

/users/1/address~1street        ← a property inside an object
/filters/~0temp~1fan            ← a key containing ~ and /
/schema/properties/name         ← three levels deep
/items/0                        ← first element of an array
                                ← (empty string: the whole document)

Three properties of the format matter for everything that follows. First, the empty string is a valid pointer — it addresses the entire document. Second, every non-empty pointer begins with /, so the first token is always the substring between position one and the next slash. Third, reference tokens are plain strings with no quoting mechanism of any kind: no backslash escapes, no double-quote delimiters, no percent-encoding inside the pointer itself. Any Unicode character may appear inside a token, including the two characters the format itself needs — the slash and the tilde. That collision is the reason escapes exist at all.

Why the slash separator forces escapes

The slash is doing double duty in a JSON Pointer. It separates tokens, and nothing else is allowed to separate them. But JSON object keys can contain slashes — address/street, config/prod/v2, a URL stored as a property name, a file path assembled from CSV rows. The format needed a way to let a token contain a slash without that slash being read as a separator.

There were two possible designs. One is a quoting syntax, like wrapping a token in quotes or using a backslash, as \/ does inside JSON strings. RFC 6901 chose the other design: a two-character escape prefix. The tilde ~ becomes the escape character, which creates a second collision — keys can contain tildes too — so the tilde needs its own escape. That is the complete set: two sequences, no more. If you have worked with URL encoding before, the shape of the problem will feel familiar; we have a separate guide on forward-slash escaping that covers the same collision in the URL world, where the slash also separates path segments.

The design is deliberately minimal. There is no third escape, no hex notation, no way to encode anything except these two characters. A token containing a newline, a unicode emoji, or a percent sign needs no escaping at all — it passes through literally. Only slash and tilde get transformed, which keeps the decode step tiny but also means the decode step has nowhere to hide mistakes. Two sequences, one order, no second chances.

The two escape sequences: ~1 and ~0

On the encoding side, each tilde in a real key becomes ~0, and each slash becomes ~1. The digits are arbitrary but memorable if you squint: 1 resembles the slash it stands for, and 0 is the escape for the escape character itself. Decoding reverses the mapping.

Pointer tokenDecoded keyWhat it demonstrates
address~1streetaddress/streetA literal slash inside one key
~0temp~1fan~temp/fanBoth escapes in a single token
cost~0benefit~0ratiocost~benefit~ratioTwo tildes in one key
~0~A key that is exactly one tilde
(empty token)""The empty-string property name
33No escapes needed; index or key by context

Read the table the way an evaluator would: each row is one reference token as it appears inside a pointer string, and the middle column is the actual property name it identifies after unescaping. Nothing else in a pointer is ever transformed. A token like users or 1 contains no tilde, so it decodes to itself.

Decode order matters — tilde handling is the trap

Here is the part that breaks implementations. The two replacements are not order-independent, and the RFC specifies the order for both directions. When encoding, you must transform the tilde first, then the slash. When decoding, you must transform ~1 first, then ~0.

Why the asymmetry? Consider the encoded token ~01, which is the correct encoding of a key that reads ~1 — a tilde followed by the digit one. Decode it in the specified order and everything works: searching for ~1 finds no match (the string contains ~0, not ~1), then ~0 expands to a tilde, leaving ~1. Decode it in the wrong order and the result is garbage:

// Wrong order: ~0 replaced before ~1
"~01".replace(/~0/g, "~")    ← produces "~1"
      .replace(/~1/g, "/")   ← produces "/"  — wrong; expected "~1"

// Correct order: ~1 replaced first, then ~0
"~01".replace(/~1/g, "/")    ← no match, still "~01"
      .replace(/~0/g, "~")   ← produces "~1"  — correct

The failure mode is nasty because it is silent. A key that genuinely contains a tilde gets decoded into a slash, which the evaluator then treats as a separator, and the resolved path lands somewhere completely different in the document. Nothing throws; you just get the wrong node. The same logic drives the encoding order: if you replace slashes with ~1 before replacing tildes with ~0, the tildes you just introduced get escaped themselves, producing ~01 garbage that round-trips to the wrong key. Tilde first on the way in, ~1 first on the way out. If you remember nothing else from this guide, remember that pair.

A worked example: from error pointer to document path

Now assemble the pieces into the workflow you will actually run. Suppose a validation endpoint returns a problem-details response with a pointer field:

{
  "type": "https://api.example.com/errors/validation",
  "title": "Your payload failed schema validation",
  "status": 422,
  "errors": [
    {
      "pointer": "/users/1/address~1street",
      "message": "must not exceed 80 characters"
    }
  ]
}

The pointer claims the problem is at /users/1/address~1street. Decode it step by step, and never decode the string as a whole — always split first, then unescape each token in isolation:

Step 1. The pointer starts with /, so strip the leading slash and split the rest on /. Tokens: users, 1, address~1street. Notice that the split happens on the raw string, before any unescaping — this ordering is what keeps the encoded slash inside the third token from being mistaken for a separator.

Step 2. Unescape each token independently, applying ~1 before ~0. The first two tokens contain no tilde and pass through unchanged. The third token address~1street contains one ~1, which becomes a slash: the decoded key is address/street.

Step 3. Walk the document with the decoded tokens. Here is the payload the server was validating:

{
  "users": [
    { "name": "Ada" },
    {
      "name": "Grace",
      "address/street": "12 Enigma Lane",
      "address/city": "Portsmouth"
    }
  ]
}

Token users selects the array. Token 1 selects its second element (array indices are zero-based). Token address/street — the decoded form — selects the property literally named address/street inside that object. The error is about the character limit on "12 Enigma Lane". If instead you had decoded the pointer by splitting on every slash including the encoded one, your walk would have been users, 1, address, street — and step three would have failed with a missing property, sending you on a hunt for a schema bug that does not exist.

Keys that literally contain tildes

Tildes in real keys are rarer than slashes but not exotic: cost~benefit, approx~value, temperature sensor channels named temp~0, identifiers derived from systems that use tilde as a version separator. Each one becomes a ~0 in pointer form, and each one is a place where sloppy decoders corrupt the path.

The dangerous case is a key where a tilde is followed by a digit that looks like an escape. A key named temp~0 encodes to the token temp~00. Decode correctly and you get temp~0 back. Decode with a single unconditional replace(/~0/g, "~") applied at the wrong stage — or run the decoder twice, which we will come back to — and the key shifts. The practical defense is to treat every pointer string as encoded until the moment of evaluation, and to unit-test your decoder against the awkward set: ~1, ~0, ~01, ~~, and a key that is a single tilde. Five test cases cover essentially every real-world decoder bug.

One more subtlety worth knowing: ~ followed by anything other than 0 or 1 is not a defined escape under RFC 6901. Strict implementations either fail the pointer or leave the sequence untouched. Lenient ones pass it through, which is usually fine in practice — but it means a pointer like /a~2b is either invalid or means a~2b, never a2b or anything else. Do not invent third escapes in your own tools; downstream consumers will not understand them.

Building pointers programmatically: the encode side

So far this guide has read pointers. Tools that validate, patch, or diff JSON also write them, and writing them is where encode-order bugs creep in. The rule from earlier applies: escape the tilde first, then the slash. A correct encoder is four lines:

function encodeToken(key) {
  // RFC 6901 order: tilde first, then slash
  return key.replace(/~/g, "~0").replace(/\//g, "~1");
}

function buildPointer(keys) {
  // keys: array of property names / array indices, in walk order
  return keys.map(encodeToken).join("/");
}

This comes up constantly when you generate documents from tabular data. Flatten a nested object with the encoded token as part of the flattened key, and the pointer for any leaf can be rebuilt from the key parts with buildPointer. The same trap appears here in mirror image: if your flattener joins keys with / before encoding, a key containing a slash becomes indistinguishable from two levels, and no decoder can undo that — the information is gone. Encode each token, then join. Never join, then encode, and never join raw keys that might contain the separator.

Array indices serialize as their plain decimal string: the third element of an array is 2, not [2] or /2 inside the token. There is no notation for a range, a slice, or a wildcard — a pointer names exactly one node. If you find yourself wanting /items/*/id, you want iteration over pointers, not a richer pointer syntax.

The empty-string key and array indices

Two edge cases round out the format, and both show up in error pointers more often than you would expect.

The first is the empty string. As noted earlier, an empty pointer addresses the whole document. Less obvious: the empty string is also a legal object key — {"": "surprise"} is valid JSON — and a pointer token can encode it too. Splitting /a//b on slashes yields three tokens: a, empty, b. The middle token selects the property named "". This means your decoder must not filter out empty tokens, collapse consecutive slashes, or trim the string. JavaScript's split("/") preserves empty segments, which is exactly the behavior you need; many hand-rolled splitters in other languages do not, and silently corrupt such pointers.

The second is array indices. When the current node is an array, the token must be a decimal number with no leading zeros — 0, 1, 17 are valid; 01 is not, and +1 is not. Why the strictness? Because 01 would be ambiguous: is it index one, or a property named "01"? RFC 6901 resolves the ambiguity by declaring that any token that is not a valid zero-padded-free index fails evaluation on an array. A token like - is special: it is invalid for reading, but JSON Patch gives it meaning on the add operation, where it means "append at the end."

Common mistakes that break paths

Three failure patterns account for nearly every broken pointer handling you will encounter in code review.

Decoding before splitting

The most common mistake runs the escape replacements over the entire pointer string first and splits on / afterward. That order turns the encoded slash inside address~1street into a real separator, producing a four-token walk instead of a three-token walk. The correct order is the reverse: split the raw pointer on /, then unescape each token with ~1 before ~0. Splitting first is safe precisely because the encoding guarantees that a genuine separator can never be disguised inside a token — every literal slash in a key is stored as ~1, so every bare / in the string really is a boundary.

The mirror mistake is splitting without decoding at all, which produces tokens containing raw ~1 and ~0 sequences that match no property in any well-formed document.

Double decoding

The second mistake is applying the unescape transformation twice — once in a shared utility, once in a call site that forgot the utility already handles it. Double decoding turns the encoded form of the key ~1 (the token ~01) into the key /, and it turns the token ~01 from the example above into garbage. The tell-tale symptom is that pointers work for simple paths and fail only on keys containing tildes or slashes. A useful invariant to test: decode(encode(key)) === key must hold for every key, and encode(decode(token)) === token must hold for every well-formed token. If either fails, one side is decoding twice.

Treating a pointer as a URL fragment

The third mistake conflates the pointer with its URI fragment representation. Pointers often appear inside URIs — OpenAPI schema references, Location headers, documentation links — written as #/users/1/address~1street. In that context the leading # is fragment syntax and everything after it should additionally be percent-encoded per RFC 3986: a space becomes %20, a plus stays a literal plus, non-ASCII characters become UTF-8 percent sequences. If you run the fragment through a query-string decoder, plus signs get turned into spaces and the pointer breaks in ways that only appear for keys containing + or %. The rule: strip the #, percent-decode once (only if the pointer came from a URI), then treat the remainder as a plain pointer and decode its tokens. Percent-decoding a pointer that never lived inside a URI is a bug — a key literally named 100%25 would come out wrong.

Pointers in JSON Patch and diff output

Two standard consumers make pointer fluency non-optional. The first is JSON Patch (RFC 6902), where every operation addresses its target with a pointer, and move and copy carry two:

[
  { "op": "replace", "path": "/users/1/address~1street", "value": "13 Enigma Lane" },
  { "op": "add", "path": "/users/-", "value": { "name": "Linus" } },
  { "op": "remove", "path": "/users/0" }
]

The replace in this patch would silently do nothing on a decoder that mishandles ~1 — JSON Patch implementations typically ignore operations whose path fails to resolve, rather than throwing. That makes pointer bugs in patch pipelines particularly quiet: documents drift, tests still pass, and the corruption surfaces days later as a data mismatch.

The second consumer is any diff tool that compares two JSON documents and reports their differences. A useful diff output format names each changed node by pointer, because a pointer is re-usable: you can feed it straight into a patch path, log it, or resolve it against the original document to show before-and-after values. When you read a diff, the same decode discipline applies — the pointer in the diff output is encoded, so a change to the key address/street will be reported as /address~1street, and pasting that into a search box un-decoded will find nothing.

Test it yourself

The fastest way to internalize the mechanism is to break a few pointers on purpose. Paste a document with keys containing slashes and tildes into the JSON Inspector, resolve the pointer /users/1/address~1street against the worked example above, and confirm you land on the street value. Then mutate the pointer — drop the escape, decode in the wrong order, add a leading zero to an array index — and watch exactly which level of the walk fails. The same experiment works well for diff workflows: run two slightly different documents through JSON Compare, take the pointers it reports, and check that each one resolves against the original document. Five minutes of deliberate failure teaches the decode order better than any specification section.

Reproduce every example locally with the JSON Inspector or the matching tool on the workbench. Nothing you paste leaves your browser.