skip to Main Content

I have the following input file

["alice", ["foo", "bar", "baz"]]
["bob", ["qux", "quux"]]
⋮

and I want to convert it to a tab separated file that looks like the following (note the lack of quotes)

alice   foo
alice   bar
alice   baz
bob     qux
bob     quux
⋮

All the array elements are guaranteed to be strings (no nulls).
Can you help me come up with a jq script to achieve this?

2

Answers


  1. Replace the last item (or equally the .[1] item) with each of its own items (.[]), then turn all of it into tab-separated values using @tsv:

    jq -r 'last = last[] | @tsv' input.json
    
    alice   foo
    alice   bar
    alice   baz
    bob qux
    bob quux
    

    Demo

    Login or Signup to reply.
  2. Here’s another way to do it by placing the first element in an array and then using the built-in combinations.

    jq --raw-output '.[0]=[.[0]] | combinations | @tsv' input.json
    

    Try it on jqplay.org.

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