/ Bash

Search JSON array with JQ

JQ is a powerful command-line JSON processing tool. It's super fast (C), provides solid documentation, and is easy to use. In this example, given a JSON object from a file, curl response; we look through an array nested inside an object, and return a matching object within the array. I want to lookup the id of an item, given the name.

{
    "ok": true,
    "items": [
        {"id": 123, "name": "thing-1"},
        {"id": 124, "name": "thing-2"},
        {"id": 125, "name": "thing-3"}
    ]
}

We can pipe a filter result within the JQ sequence with the | character, just like a standard shell interface. The select command then searches a match pattern within an iterable array.

cat file.json | jq '.items[] | select(.name == "thing-3") | .'

The final select result is piped and formatted as needed. For example, we can use the -r (raw output) option to return unformatted (not quoted) output, and ONLY the id field.

cat file.json | jq -r '.items[] | select(.name == "thing-3") | .id'

There are numerous useful operators and functions provided in the documentation. JQ also provides a fantastic playground here.