Skip to main content

jq: select

Official Documentation

missing array fields#

Similar to something like javascript optional chaining , the select operator can work on array fields that might or might not exist.

Input: '{"x": {"y": [1,2,3], "z": [4,5]}}'
jq '.x.y[]'
Output: 1
2
3
jq '.x.a[]'
Output: jq: error (at <stdin>:1): Cannot iterate over null (null)

Using select to deal with missing fields.

Input: '{"x": {"y": [1,2,3], "z": [4,5]}}'
jq '.x|select(.y).y[]'
Output: 1
2
3
jq '.x|select(.a).a[]'
Output:

The alternative operator can be used in this example as well. Not sure which ends up being more readable.

Input: '{"x": {"y": [1,2,3], "z": [4,5]}}'
jq '.x|(.y//[])[]'
Output: 1
2
3
jq '.x|(.a//[])[]'
Output: