Skip to content

Commit 07adae8

Browse files
authored
JSON Pointer
1 parent 07cfd6c commit 07adae8

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

json/json-pointer.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# JSON Pointer
2+
3+
I'm [looking at options](https://github.com/simonw/datasette/issues/1875) for representing JSON validation errors in more JSON. The recent [RFC 7807: Problem Details for HTTP APIs](https://datatracker.ietf.org/doc/draft-ietf-httpapi-rfc7807bis/) looks relevant here.
4+
5+
It uses [JSON Pointer](https://www.rfc-editor.org/rfc/rfc6901) to indicate where in a nested JSON object an error occurred. So I need to figure that out.
6+
7+
With the help of GPT-3 I made the following notes:
8+
9+
Given this JSON:
10+
```json
11+
{
12+
"name": "Bob",
13+
"inner": {
14+
"age": 30,
15+
"ties": ["blue", "black"],
16+
"1": "one"
17+
}
18+
}
19+
```
20+
The JSON Pointer to the name is:
21+
22+
/name
23+
24+
The JSON Pointer to the ties is:
25+
26+
/inner/ties
27+
28+
The JSON Pointer to "one" is:
29+
30+
/inner/1
31+
32+
This last one is tricky: how can you tell the difference between an index into an array and the name of a key?
33+
34+
Turns out the answer is to look at whether you are dealing with an object or an array at the time when you are processing the pointer.
35+
36+
Here's [where that is implemented](https://github.com/stefankoegl/python-json-pointer/blob/a95c26fba8ef44af6d16ad6c5b70d7f9c69ae36c/jsonpointer.py#L272-L288) in the [python-json-pointer](https://github.com/stefankoegl/python-json-pointer) library.
37+
38+
(GPT-3 wrote the rest of this.)
39+
40+
## JSON Pointer escape sequences
41+
42+
The JSON Pointer escape sequences are:
43+
44+
- `/` is escaped by `~1`
45+
- `~` is escaped by `~0`
46+
47+
This means that the JSON Pointer `/inner/~0/1` is actually `/inner/~/1`,
48+
which points to the value `"one"` in the example JSON.
49+
50+
[ Simon note: I didn't fully understand this example ]
51+
52+
## JSON Pointer evaluation
53+
54+
To evaluate a JSON Pointer:
55+
56+
1. Split the JSON Pointer on `"/"` to get the parts.
57+
2. Start with the root value (where the pointer was given)
58+
3. For each part:
59+
1. If the part is `"~1"`, replace it with `"/"`
60+
2. If the part is `"~0"`, replace it with `"~"`
61+
3. If the part is `"0"` through `"9"`, take the corresponding element of the current value.
62+
4. Otherwise, take the value of the field with this name in the current value.
63+
4. The result is the value

0 commit comments

Comments
 (0)