Standardadvanced
JSON Pointer
Also called RFC 6901, JSON pointer path.
JSON Pointer (RFC 6901) is a string such as /users/0/name that identifies one value inside a JSON document. JSON Patch, JSON Schema and many APIs use it to name a location.
What it is
JSON Pointer is a string syntax that identifies one value inside a JSON document. RFC 6901 defines it as "a string syntax for identifying a specific value within a JavaScript Object Notation (JSON) document"1. The pointer /users/0/name means: in the root object, take the member users, then the element at index 0 of that array, then the member name of that object.
A pointer is a path of keys and indexes, written as text. The text form lets one JSON document refer to a location in another one. JSON Patch uses a pointer in each operation: an operation object "MUST have exactly one "path" member", and the value of that member is "a string containing a JSON-Pointer value"2. JSON Schema uses pointers in URI fragments, so "$ref": "#/$defs/positiveInteger" refers to a subschema in the same document3. The output format of JSON Schema also reports the location of a bad value as a pointer: the instance location "MUST be expressed as a JSON Pointer"3.
JSON Pointer is not a query language. RFC 9535, which defines JSONPath, says that "JSON Pointer is for identifying a single value within a JSON value whose structure is known"4. A pointer has no wildcards and no filters. It identifies one value, or it fails.
Syntax or structure
A pointer is "a sequence of zero or more reference tokens, each prefixed by a '/' (%x2F) character"1. The grammar in ABNF is:
json-pointer = *( "/" reference-token )
reference-token = *( unescaped / escaped )
unescaped = %x00-2E / %x30-7D / %x7F-10FFFF
escaped = "~" ( "0" / "1" )
array-index = %x30 / ( %x31-39 *(%x30-39) )
The rules of the grammar and of the evaluation are these1:
- The empty string identifies the whole document. The pointer
/is not the root. It identifies the member whose name is the empty string. - A
~in a member name is written as~0, and a/is written as~1. To decode a token, an evaluator replaces~1with/first, and then~0with~. - On an object, a token selects the member with that name. The names are compared code point by code point, with no Unicode normalization.
- On an array, a token must be
0or a decimal number with no leading zero. The token-refers to "the (nonexistent) member after the last array element". - A pointer that does not match the grammar, or that refers to a value that does not exist, is an error. RFC 6901 does not say how an application handles the error1.
A pointer has two text forms. In a JSON string, the usual JSON escapes apply, so the pointer /i\j is written as "/i\\j". In a URI fragment, the pointer is encoded as UTF-8 and percent-encoded, so /c%d becomes #/c%25d1.
Examples
The function resolve below follows the evaluation steps of RFC 6901. The test document and the pointers are the examples of section 5 of the RFC1. The last lines show the errors: a pointer with no leading /, an index with a leading zero, the token -, an index past the end and an escape that is not ~0 or ~1.
import json
import re
INDEX = re.compile(r"0|[1-9][0-9]*")
def resolve(doc, pointer):
"""Returns the value that an RFC 6901 pointer identifies in doc."""
if pointer == "":
return doc
if not pointer.startswith("/") or re.search(r"~(?![01])", pointer):
raise ValueError(f"bad pointer {pointer!r}")
value = doc
for token in pointer[1:].split("/"):
token = token.replace("~1", "/").replace("~0", "~")
if isinstance(value, dict) and token in value:
value = value[token]
elif isinstance(value, list) and INDEX.fullmatch(token) and int(token) < len(value):
value = value[int(token)]
else:
raise LookupError(f"no value at {pointer!r}")
return value
def escape(name):
"""Turns a member name into a reference token."""
return name.replace("~", "~0").replace("/", "~1")
doc = json.loads(r'''{"foo": ["bar", "baz"], "": 0, "a/b": 1, "c%d": 2, "e^f": 3,
"g|h": 4, "i\\j": 5, "k\"l": 6, " ": 7, "m~n": 8}''')
for p in ["/foo", "/foo/0", "/", "/a~1b", "/c%d", "/e^f", "/g|h", "/i\\j", '/k"l', "/ ", "/m~0n"]:
print(f"{p!r:10} {json.dumps(resolve(doc, p))}")
print("/" + escape("m~n"), "/" + escape("a/b"))
for p in ["foo", "/foo/01", "/foo/-", "/foo/2", "/x~2y"]:
try:
resolve(doc, p)
except (ValueError, LookupError) as error:
print(type(error).__name__, error)
'/foo' ["bar", "baz"]
'/foo/0' "bar"
'/' 0
'/a~1b' 1
'/c%d' 2
'/e^f' 3
'/g|h' 4
'/i\\j' 5
'/k"l' 6
'/ ' 7
'/m~0n' 8
/m~0n /a~1b
ValueError bad pointer 'foo'
LookupError no value at '/foo/01'
LookupError no value at '/foo/-'
LookupError no value at '/foo/2'
ValueError bad pointer '/x~2y'
The function escape makes a token from a member name. It replaces ~ before /, the reverse of the decode order. The example files of this page show the same resolver in other languages:
- JavaScript.
JSON.parsegives plain objects. The resolver checksObject.hasOwn, so the pointer/constructordoes not find a property ofObject.prototype. - Go.
json.Unmarshalintoanygives maps and slices, and a type switch walks them. - C#.
System.Text.Json.Nodesgives a tree of nodes.TryGetPropertyValuetells a member with the valuenullfrom a member that does not exist.
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
JsonNode? doc = JsonNode.Parse("""{"items": [{"id": 7, "tags": ["new"]}], "a/b": null}""");
foreach (string p in new[] { "/items/0/id", "/items/0/tags", "/a~1b", "/items/7", "/missing" })
{
try
{
JsonNode? v = Resolve(doc, p);
Console.WriteLine($"{p} {v?.ToJsonString() ?? "null"}");
}
catch (KeyNotFoundException e)
{
Console.WriteLine($"{p} error: {e.Message}");
}
}
// Resolve returns the node that an RFC 6901 pointer identifies. A JSON null is a C# null.
static JsonNode? Resolve(JsonNode? doc, string pointer)
{
if (pointer == "") return doc;
if (!pointer.StartsWith('/')) throw new FormatException($"bad pointer {pointer}");
JsonNode? value = doc;
foreach (string raw in pointer[1..].Split('/'))
{
string token = raw.Replace("~1", "/").Replace("~0", "~");
if (value is JsonObject obj && obj.TryGetPropertyValue(token, out JsonNode? member))
value = member;
else if (value is JsonArray arr && Regex.IsMatch(token, "^(0|[1-9][0-9]*)$") && int.TryParse(token, out int i) && i < arr.Count)
value = arr[i];
else
throw new KeyNotFoundException($"no value at token {token}");
}
return value;
}
/items/0/id 7
/items/0/tags ["new"]
/a~1b null
/items/7 error: no value at token 7
/missing error: no value at token missing
- Verdict: stdlib.
System.Text.Json.Nodesgives a mutable tree ofJsonObject,JsonArrayandJsonValuenodes, and the resolver walks it one token at a time. The library has no JSON Pointer function, so the code follows the evaluation steps of RFC 6901. A JSONnullis a C#nullin this tree, so the resolver usesTryGetPropertyValueto tell a member with the valuenull(/a~1b) from a member that does not exist (/missing).
const INDEX = /^(0|[1-9][0-9]*)$/;
// resolve returns the value that an RFC 6901 pointer identifies in doc.
function resolve(doc, pointer) {
if (pointer === "") return doc;
if (!pointer.startsWith("/") || /~(?![01])/.test(pointer)) {
throw new SyntaxError(`bad pointer ${JSON.stringify(pointer)}`);
}
let value = doc;
for (const raw of pointer.slice(1).split("/")) {
const token = raw.replaceAll("~1", "/").replaceAll("~0", "~");
if (Array.isArray(value)) {
if (!INDEX.test(token) || Number(token) >= value.length) {
throw new RangeError(`no element ${token}`);
}
value = value[Number(token)];
} else if (value !== null && typeof value === "object" && Object.hasOwn(value, token)) {
value = value[token];
} else {
throw new RangeError(`no member ${JSON.stringify(token)}`);
}
}
return value;
}
const doc = JSON.parse('{"users": [{"name": "Ana", "roles": ["admin"]}], "a/b": 1}');
console.log(resolve(doc, "/users/0/name"));
console.log(JSON.stringify(resolve(doc, "/users/0/roles")));
console.log(resolve(doc, "/a~1b"));
// A plain lookup with value[token] also finds inherited properties.
console.log(typeof doc["constructor"]);
for (const p of ["/constructor", "/users/1", "/users/00"]) {
try {
resolve(doc, p);
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}
}
Ana
["admin"]
1
function
RangeError: no member "constructor"
RangeError: no element 1
RangeError: no element 00
- Verdict: native.
JSON.parsegives plain objects and arrays, and the resolver walks them one token at a time. The language has no function that resolves a JSON Pointer. The resolver usesObject.hasOwn, because a plain lookupvalue[token]also finds the inherited properties ofObject.prototype. Without the check, the pointer/constructorgives a function, which is not a JSON value.replaceAlldecodes~1before~0, in the order that RFC 6901 gives.
package main
import (
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
)
var index = regexp.MustCompile(`^(0|[1-9][0-9]*)$`)
// resolve returns the value that an RFC 6901 pointer identifies in doc.
func resolve(doc any, pointer string) (any, error) {
if pointer == "" {
return doc, nil
}
if !strings.HasPrefix(pointer, "/") {
return nil, fmt.Errorf("bad pointer %q", pointer)
}
value := doc
for _, raw := range strings.Split(pointer[1:], "/") {
token := strings.ReplaceAll(strings.ReplaceAll(raw, "~1", "/"), "~0", "~")
switch v := value.(type) {
case map[string]any:
next, ok := v[token]
if !ok {
return nil, fmt.Errorf("no member %q", token)
}
value = next
case []any:
if !index.MatchString(token) {
return nil, fmt.Errorf("bad index %q", token)
}
i, err := strconv.Atoi(token)
if err != nil || i >= len(v) {
return nil, fmt.Errorf("no element %s", token)
}
value = v[i]
default:
return nil, fmt.Errorf("token %q applied to a %T", raw, value)
}
}
return value, nil
}
func main() {
var doc any
json.Unmarshal([]byte(`{"servers": [{"host": "a.example", "port": 8080}], "m~n": true}`), &doc)
for _, p := range []string{"/servers/0/host", "/servers/0/port", "/m~0n", "/servers/0/port/x", "/servers/-"} {
v, err := resolve(doc, p)
if err != nil {
fmt.Println(p, "error:", err)
continue
}
out, _ := json.Marshal(v)
fmt.Println(p, string(out))
}
}
/servers/0/host "a.example"
/servers/0/port 8080
/m~0n true
/servers/0/port/x error: token "x" applied to a float64
/servers/- error: bad index "-"
- Verdict: stdlib.
json.Unmarshalintoanygivesmap[string]any,[]anyand scalar values, and a type switch walks them one token at a time. The packageencoding/jsonhas no function that resolves a JSON Pointer. A JSON number becomes afloat64, so a token after the port number has no container to apply to. The token-names the place after the last element, so it is never a value.
Versions
RFC 6901 was published in April 2013, together with RFC 6902 (JSON Patch)12. It has no later version. Its references to JSON point to RFC 4627, an older JSON specification, but the pointer rules do not depend on the version of JSON.
Some applications add rules of their own. RFC 6902 uses the token - to append to an array: "If the "-" character is used to index the end of the array (see [RFC6901]), this has the effect of appending the value to the array"2. RFC 9535 says that a Normalized JSONPath "can be converted into a JSON Pointer by converting the syntax, without knowledge of any JSON value", but the reverse is not always possible, because a numeric token can name an array element or an object member4.
Pitfalls
- The decode order matters. If an evaluator replaces
~0first, the token~01becomes~1and then/. The correct result is~1, the name of a member that has a tilde and a one in it1:
This code runs but gives a wrong answer on purpose.
def wrong(token):
return token.replace("~0", "~").replace("~1", "/")
def right(token):
return token.replace("~1", "/").replace("~0", "~")
# The member name "~1" is written as the token "~01".
print(wrong("~01"), right("~01"))
/ ~1
- A numeric token is not always an index. On the object
{"0": "x"}, the pointer/0selects the member named0. The meaning of a token depends on the value that the evaluator is at, not on the text of the token4. /is not the root. The root is the empty pointer./refers to the member with the empty name.-is never a value. A plain lookup of/items/-is always an error1. Only an application such as JSON Patch gives it a meaning2.- Leading zeros.
/items/01is an error, but a careless parser that calls a general integer function accepts it as index 1. Check the token against thearray-indexrule before you convert it. - Inherited properties in JavaScript. A lookup with
value[token]on a parsed object also finds properties such asconstructorand__proto__. CheckObject.hasOwnbefore each step, as in the JavaScript example. - Two encodings in a URI. In a URI fragment,
~1stays as it is, but%must become%25. Do not mix the percent encoding of the URI with the tilde escapes of the pointer1. - Duplicate member names. If a referenced name is not unique in an object, the referenced member "is undefined, and evaluation fails"1. Check for duplicate names when the input is not trusted.
Tools and libraries
- Python: the library
jsonpointer, withresolve_pointer(obj, pointer)5. - Rust:
serde_json::Value::pointer, which "Looks up a value by a JSON Pointer" and returnsNonewhen there is no such value6. - Java: the interface
jakarta.json.JsonPointerof Jakarta JSON Processing. Its methodsadd(),replace()andremove()"execute operations specified in RFC 6902"7. - JavaScript, Go and C#: the standard libraries have no pointer function. The resolvers in the examples are short, and libraries for each language exist.
The page JSON Patch and JSON Merge Patch uses pointers to name the targets of its operations, and JSONPath covers the query language that selects many values.
References
- P. Bryan (Ed.), K. Zyp, M. Nottingham (Ed.), RFC 6901: JavaScript Object Notation (JSON) Pointer, April 2013, 3 Syntax; 4 Evaluation; 5 JSON String Representation; 6 URI Fragment Identifier Representation; 7 Error Handling
- P. Bryan (Ed.), M. Nottingham (Ed.), RFC 6902: JavaScript Object Notation (JSON) Patch, April 2013, 4 Operations; 4.1 add
- A. Wright, H. Andrews, B. Hutton, G. Dennis, JSON Schema: A Media Type for Describing JSON Documents, draft 2020-12, 5 Fragment Identifiers; 8.2.4 Schema Re-Use With "$defs"; 12.3.3 Instance Location
- S. Gössner, G. Normington, C. Bormann (Ed.), RFC 9535: JSONPath: Query Expressions for JSON, February 2024, Appendix C JSON Pointer
- python-json-pointer documentation, Tutorial, resolve_pointer
- serde_json documentation, enum Value, Value::pointer; Value::pointer_mut
- Jakarta JSON Processing 2.1 API, interface JsonPointer, the interface description; Method Summary
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag NZAZBX Edit this page History Report an error Markdown