Beta

Create a tenant

A new tenant starts with its own users, OAuth settings, audit history and logs. You are its first Tenant Admin.

Reading JSON from APIs with jq

APIs answer with JSON, a small set of value types nested into a tree. jq reads that tree from the terminal: it lays it out, walks a path to the value you want, filters and reshapes lists, and hands the result to the shell as plain text or as an exit status.

What JSON looks like

When a weather app shows tomorrow's forecast, it did not receive a finished screen. It asked a server for the forecast, got back plain data, and drew the screen itself. Most of the time that data is JSON, the text format for structured data from How applications communicate. Identity systems use it everywhere: in API responses, in configuration documents and inside tokens.

Here is how a photo service might describe one photo:

{
  "id": "p1",
  "title": "Harbor at dawn",
  "width": 4032,
  "favorite": true,
  "location": null,
  "tags": ["sea", "morning"],
  "owner": {"name": "Ava Archer", "email": "[email protected]"}
}

JSON has only a few kinds of value, and this example uses all of them:

  • An object, written with braces, holds pairs of a name and a value, separated by commas. The names, often called keys, are always strings. The whole photo is an object, and so is owner.
  • An array, written with square brackets, is an ordered list of values, such as tags.
  • A string is text in double quotes, such as "Harbor at dawn".
  • A number has no quotes, such as 4032. "4032" in quotes would be a string that happens to contain digits.
  • true and false are yes-or-no values, and null means "no value", like the photo's unknown location.

Objects and arrays can hold any of these values, including other objects and arrays, so a JSON document is really a tree: an album holds a list of photos, each photo holds a list of tags and an object describing its size. The rules are strict. Strings and keys need double quotes, not single ones, and a comma after the last item in an object or array makes the whole document invalid.

Pretty printing with jq

Outside strings, spaces and line breaks mean nothing to JSON, so services usually leave them out to keep responses small. Ask a photo API for an album with curl, as in Sending requests with curl, and the answer arrives as one long line:

$ curl -sS https://api.photos.example/albums/a1
{"album":{"id":"a1","title":"Summer trip","photos":[{"id":"p1","title":"Harbor at dawn","tags":["sea","morning"],"size":{"width":4032,"height":3024}},{"id":"p2","title":"Market stalls","tags":["city"],"size":{"width":3024,"height":4032}},{"id":"p3","title":"Lighthouse","tags":["sea","evening"],"size":{"width":4032,"height":3024}}],"owner":{"name":"Ava Archer","email":"[email protected]"}}}

jq is a command for reading and reshaping JSON. You give it a small program, called a filter, and it applies the filter to the JSON it reads. The simplest filter is a single dot, which means "the whole input, unchanged". jq prints its result laid out with one value per line and two spaces of indentation for each level, so the shape of the tree becomes visible. Pipe the response into it:

curl -sS https://api.photos.example/albums/a1 | jq .
{
  "album": {
    "id": "a1",
    "title": "Summer trip",
    "photos": [
      {
        "id": "p1",
        "title": "Harbor at dawn",
        "tags": [
          "sea",
          "morning"
        ],
        "size": {
          "width": 4032,
          "height": 3024
        }
      },
      {
        "id": "p2",
        "title": "Market stalls",
        "tags": [
          "city"
        ],
        "size": {
          "width": 3024,
          "height": 4032
        }
      },
      {
        "id": "p3",
        "title": "Lighthouse",
        "tags": [
          "sea",
          "evening"
        ],
        "size": {
          "width": 4032,
          "height": 3024
        }
      }
    ],
    "owner": {
      "name": "Ava Archer",
      "email": "[email protected]"
    }
  }
}

In a terminal, jq also colors keys, strings and numbers differently. It reads from a pipe, as here, or from a file whose name you give after the filter. The rest of this lesson saves the response once with curl -sS -o album.json and reads the file, so each example does not need a new request:

jq . album.json

jq checks the input as it reads it. If the input is not valid JSON, it stops with a parse error instead of guessing. That often means the server sent something else, such as an HTML error page. Look at the status and headers with curl -i before blaming the filter.

Picking out values

Most of the time you want one part of a response, not all of it. A dot followed by a key picks that key's value out of an object, and you can chain keys to walk down the tree:

$ jq '.album.title' album.json
"Summer trip"

Put the filter in single quotes. jq filters use characters that bash treats specially, such as |, [ and $, and single quotes pass them to jq untouched, as Variables, quoting and the environment explained.

The answer still has its double quotes, because jq prints JSON, and in JSON a string is written in quotes. The -r option, for raw output, prints strings as plain text instead, which is what you want when the value goes into another command or a variable:

$ jq -r '.album.title' album.json
Summer trip

Arrays are read by position. .album.photos[0] is the first photo, because positions count from zero, and .album.photos[0].title continues from there to its title. Empty brackets, [], take every item in the array one at a time, and whatever follows applies to each item in turn:

$ jq -r '.album.photos[].title' album.json
Harbor at dawn
Market stalls
Lighthouse

A key that does not exist is not an error. jq answers null, so a misspelled key such as .album.titel quietly prints null. When a result is unexpectedly null, check the spelling and the path first. Asking an array for a key, on the other hand, is an error: .album.photos.title fails with Cannot index array with string "title", because photos is a list and needs [0] or [] before .title.

The input

"album": {

"title": "Summer trip",

"photos": [

{"title": "Harbor at dawn", ...},

{"title": "Market stalls", ...},

{"title": "Lighthouse", ...} ] }

What each path returns

.album.title
"Summer trip"
.album.photos[0].title
"Harbor at dawn"
.album.photos[].title
Harbor at dawn, Market stalls, Lighthouse
.album.titel
null
.album.photos.title
Cannot index array with string "title"

A key that does not exist is not an error. jq answers null

When a result is unexpectedly null, check the spelling and the path first.

The same album read with five paths. A misspelled key gives null; a key asked of an array is an error.

Filtering and shaping results

Inside a jq filter, | works like the pipe in the shell: the output of the filter on its left becomes the input of the one on its right. jq has built-in functions that make this useful. length counts the items in an array or the keys in an object, and keys lists an object's keys in alphabetical order:

$ jq '.album.photos | length' album.json
3
$ jq -c '.album | keys' album.json
["id","owner","photos","title"]

The -c option asks for compact output, one result per line, which keeps short arrays and objects readable on a single line.

select keeps only the values that pass a test and drops the rest. Inside the test, . is the value being checked. Here jq takes each photo in turn and keeps the ones that are wider than they are tall:

$ jq -r '.album.photos[] | select(.size.width > .size.height) | .title' album.json
Harbor at dawn
Lighthouse

Tests compare with ==, !=, < and >, and combine with and, or and not. To ask whether an array contains a value, any(.tags[]; . == "sea") goes through each tag and is true when at least one of them equals "sea":

$ jq -r '.album.photos[] | select(any(.tags[]; . == "sea") and .size.width > .size.height) | .id' album.json
p1
p3

map applies a filter to every item of an array and collects the results into a new array. That keeps the answer as one JSON value, so you can carry on with it, for example to count how many photos are tagged sea:

$ jq -c '.album.photos | map(.id)' album.json
["p1","p2","p3"]
$ jq '.album.photos | map(select(any(.tags[]; . == "sea"))) | length' album.json
2

You can also build new objects from the values you pick. Braces with id on its own copy the id key, and width: .size.width creates a new key from a nested value:

$ jq -c '.album.photos[] | {id, width: .size.width}' album.json
{"id":"p1","width":4032}
{"id":"p2","width":3024}
{"id":"p3","width":4032}

Using jq with curl and the shell

jq is at its best in a pipeline. curl -sS prints only the response body, or a short error if the request itself fails, so it feeds jq cleanly. With -r, the result is ordinary text that command substitution can store in a shell variable:

owner=$(curl -sS https://api.photos.example/albums/a1 | jq -r '.album.owner.email')
echo "$owner"

When a filter prints several results, one per line, read them with while read -r, which takes one whole line at a time. for title in $(...) would split Harbor at dawn into three words: the word splitting Searching and shaping text warned about with for line in $(cat ...):

jq -r '.album.photos[].title' album.json | while read -r title; do
  echo "Printing: $title"
done

A script often needs a yes or no rather than a value. The -e option sets jq's exit status from its last result: 0 when the result is anything but false or null, and non-zero when it is one of those or when there is no result at all. That makes a jq test usable as the condition of an if, and > /dev/null hides the true it prints:

if jq -e '.album.photos | length > 0' album.json > /dev/null; then
  echo "The album has photos"
else
  echo "The album is empty"
fi

Sometimes the filter needs a value from the shell, such as a tag the user typed. Writing $tag inside the single-quoted filter will not work, because single quotes stop bash from replacing it. Switching to double quotes would let bash paste the text straight into the program, where a stray quote or bracket breaks it, or changes what it does. --arg passes the value to jq separately instead: --arg tag evening creates a jq variable $tag that holds the string evening, and jq never treats its contents as part of the filter.

$ tag=evening
$ jq -r --arg tag "$tag" '.album.photos[] | select(any(.tags[]; . == $tag)) | .title' album.json
Lighthouse

The same idea builds JSON to send. The -n option tells jq not to read any input, so the filter builds its result from scratch, using the values you pass in. jq writes the quotes and escapes itself, so a title such as Ava's "best" shot still comes out as valid JSON:

$ jq -n -c --arg title "Ava's \"best\" shot" '{title: $title, done: false}'
{"title":"Ava's \"best\" shot","done":false}

Pipe that into curl --json @-, where @- means "read the body from standard input", and the request body is valid JSON whatever the title contains, because jq wrote every quote in it.

Check your understanding

Try these questions before moving on. If an answer isn't right, use the feedback and try again.

A script runs type=$(jq '.token.type' response.json) on {"token": {"type": "Bearer"}}, then tests [[ "$type" == Bearer ]]. The test fails. Why? 1 of 3

Choose one answer.

users.json holds {"users": [...]}, and each user has an "active" flag. Which filter prints only the active users' emails, one per line? 2 of 3

Choose one answer.

A script filters photos with jq "... | select(any(.tags[]; . == "$tag"))", using a tag the user typed. It works for sea, but a tag containing a double quote breaks the filter. What fixes it? 3 of 3

Choose one answer.

Try it in the Lab

We value your privacy

We use cookies and similar technologies to enhance your browsing experience, and analytics to understand our traffic. By clicking "Allow all", you consent to optional analytics. Cookie Policy

Learn identity