skip to Main Content

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


  1. The combinations function outputs all combinations of input elements. This will pair every id with every color:

    $ jq -cr '[[.id], [.colors[].color]] | combinations' test.json
    ["one","blue"]
    ["one","red"]
    ["two","green"]
    
    $ jq -r '[[.id], [.colors[].color]] | combinations | join(" ")' test.json
    one blue
    one red
    two green
    
    Login or Signup to reply.
  2. 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'
    
    Login or Signup to reply.
  3. 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:

    one blue
    one red
    two green
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search