jsonjqndjson

How to get jq to output a long dataset?


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

Solution

  • The most direct approach:

    jq -r '.id + " " + .colors[].color' my.ndjson
    

    Since you mentioned @tsv, and since @tsv output has various potential advantages, you may also wish to consider:

    .id as $id | .colors[] | [$id, .color] | @tsv
    

    Or, as @oguz_ismail suggested, if you don't want to use as at all:

    [.id]+(.colors[]|[.color])|@tsv