Suppose I have this ndjson:
{"id": "one", "colors": [{"color": "blue"}, {"color": "red"}]}
{"id": "two", "colors": [{"color": "green"}]}
How do I get the output below?
one blue
one red
two green
Here is a failed attempt:
$ cat tmp/test.json | jq -r '.id, .colors[].color'
one
blue
red
two
green
Here is a second failed attempt:
$ cat tmp/test.json | jq -r '[.id, .colors[].color]|@tsv'
one blue red
two green
3
Answers
The
combinations
function outputs all combinations of input elements. This will pair everyid
with everycolor
:The most direct approach:
Since you mentioned
@tsv
, and since @tsv output has various potential advantages, you may also wish to consider:Came up with a version here too but had to chain a few calls of jq together to make it work too, just basically pulled the parts out into new JSON objects and then parsing those and joining similar to what answer @John Kugleman posted there too (maybe not as elegant :D).
cat test.json | jq '.[] | {"id": .id, "color": .colors[].color}' | jq -r '[.[]]|join(" ")'
output like: