How to access a specific array element using jq?

Let’s assume we have following JSON document

$cat > data.json <<EOF
→ { "data" : [
→   { "key": "a", "value": 1 },
→   { "key": "b", "value": 2 }
→ ]}

Now, we want to access the value where the key is “b”. In this specific case, we can of course do so with

$ cat data.json  | jq '.data[1].value'

But this relies on the order in the array and the data itself. A more generic and stable way would be

$ cat data.json  | jq '.data[]  | select(.key == "b") | .value'

For more details on jq, you can read

Leave a comment

Your email address will not be published. Required fields are marked *