I've got JSON data that looks like this (notice that it's a list of individual objects without wrapping by []
). I would like to walk each object using jq
but it is not an array of objects. So how can I walk to each object without fixing the data to be a valid array of objects?
{
"a": 1,
"b": 2
}
{
"c": 3,
"d": 4
}
Use inputs
in combination with the --null-input
(or -n
) flag. It will provide an iteration of all inputs. Accordingly, the singular input
will fetch one input on evaluation. The --null-input
(or -n
) flag is necessary as the context .
would have already consumed the first input when reaching input
or inputs
, which then starts fetching starting from the second input. With --null-input
(or -n
) set, the context .
is bound to null
, so input
and inputs
get all the inputs available.
Example 1:
jq -n 'inputs | keys'
[
"a",
"b"
]
[
"c",
"d"
]
Example 2:
jq -n '{head: input, tail: [inputs]}'
{
"head": {
"a": 1,
"b": 2
},
"tail": [
{
"c": 3,
"d": 4
}
]
}
Note that for cases like the latter example, where the first input is treated individually, you can revert to using .
for that first input. jq '{head: ., tail: [inputs]}'
(without -n
) yields the same result (Demo).