JSON basics
JSON is the text format most APIs use to send data. It has six kinds of value and two rules about punctuation. After this page you can read any JSON response and point at any value inside it.
One example with everything in it
{
"id": 42,
"status": "shipped",
"paid": true,
"coupon": null,
"customer": {
"name": "Ada Lovelace",
"email": "ada@example.com"
},
"items": [
{ "sku": "KB-01", "name": "Mechanical keyboard", "qty": 1 },
{ "sku": "HB-07", "name": "USB-C hub", "qty": 2 }
]
}The six kinds of value
| Kind | Example | Notes |
|---|---|---|
| String | "shipped" | Text. Always in double quotes |
| Number | 42, 3.14, -7 | No quotes |
| Boolean | true, false | No quotes, lower case |
| Null | null | "No value" |
| Object | { "name": "Ada" } | Named values inside { }. Each is "name": value |
| Array | [1, 2, 3] | An ordered list inside [ ] |
Objects and arrays can hold any of the six kinds, including more objects and arrays. That nesting is all there is to JSON.
The rules people trip over
- Names and strings use double quotes.
'single'is not JSON. - Items are separated by commas, and there is no comma after the last one.
42is a number and"42"is a string. They are different values, and a test comparing them may care.- No comments.
{ "title": "Buy milk", "done": false, }That last comma makes the whole thing invalid. In ApiWorkbench, the Body tab has a Beautify JSON button that tidies valid JSON; if it does nothing, look for a stray comma or a missing quote.
Pointing at a value: paths
Tests and captures need to say which value they mean. They use a path: names joined by dots, and a number in square brackets for a position in an array. Positions start at 0.
Using the example above:
| Path | Value |
|---|---|
id | 42 |
status | shipped |
customer.name | Ada Lovelace |
items[0].sku | KB-01 |
items[1].qty | 2 |
items[2].sku | Not found: there is no third item |
When the whole response is an array, the path starts with the bracket: [0].id.
This is the path form ApiWorkbench uses in a JSON field equals test and in captures such as token = body.data.token. See Tests without code and Captures.
Reading a response in ApiWorkbench
The Pretty tab shows JSON indented and coloured, so the structure is visible. The Raw tab shows exactly the text the server sent.
Try it
Given this response:
{
"page": 1,
"users": [
{ "id": 7, "name": "Kai", "roles": ["admin", "editor"] },
{ "id": 9, "name": "Priya", "roles": [] }
]
}What are the paths to Kai's name, to the word editor, and to Priya's id?
Answers
users[0].name, users[0].roles[1] and users[1].id.
What you learned
- JSON has strings, numbers, booleans, null, objects and arrays.
- Double quotes only, and no trailing comma.
- A path such as
items[0].skupoints at one value.