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 }
→ ]}
→ EOF

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'
2

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'
2

For more details on jq, you can read https://shapeshed.com/jq-json/.

Leave a comment

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