skip to Main Content

Suppose I have this dataset:

{"id": 99, "labeled_values": [["one", "green"], ["two", "red"], ["three", "blue"]], "flavors": ["hot", "cold"]}
{"id": 100, "labeled_values": [["four", "green"], ["five", "red"]], "flavors": ["hot"]}

and I would like this output (tab-separated):

99 one green hot
99 two red hot
99 one green cold
99 two red cold
100 four green hot
100 five red hot

This code (from here) works without the flavors:

$ cat tmp/foo.ndjson | jq -r '[.id] + .labeled_values[] | @tsv'
99  one green
99  two red
99  three   blue
100 four    green
100 five    red

Here is a failed attempt to add the flavor. It concatenates all the flavors, not one at a time.

$ cat tmp/foo.ndjson | jq -r '[.id] + .labeled_values[] + .flavors | @tsv'
99  one green   hot cold
99  two red hot cold
99  three   blue    hot cold
100 four    green   hot
100 five    red hot

3

Answers


  1. Chosen as BEST ANSWER

    Here is an answer that worked, but seems ugly to me:

    $ cat tmp/foo.ndjson | jq -r '
      .id as $id |
      .labeled_values[] as $lv |
      .flavors[] as $fl |
      [$id, $lv[0], $lv[1], $fl] | @tsv' 
    99  one green   hot
    99  one green   cold
    99  two red hot
    99  two red cold
    99  three   blue    hot
    99  three   blue    cold
    100 four    green   hot
    100 five    red hot
    

  2. You can use the combinations filter:

    jq -r '[[.id],.labeled_values,.flavors] | combinations | flatten | @tsv' file.json
    
    99  one green   hot
    99  one green   cold
    99  two red hot
    99  two red cold
    99  three   blue    hot
    99  three   blue    cold
    100 four    green   hot
    100 five    red hot
    
    Login or Signup to reply.
  3. This code (from here works without the flavors:

    $ cat tmp/foo.ndjson | jq -r '[.id] + .labeled_values[] | @tsv'
    

    Just add .flavors[] and wrap each item into its own array using [.]:

    jq -r '[.id] + .labeled_values[] + (.flavors[] | [.]) | @tsv'
    
    99  one green   hot
    99  two red hot
    99  three   blue    hot
    99  one green   cold
    99  two red cold
    99  three   blue    cold
    100 four    green   hot
    100 five    red hot
    

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search