Search code examples
jsonjqtranspose

jq: how to get 2 1d arrays side by side as output


Say we have the following object in a json file:

{"a": [1,2,3], "b": [4,5,6]}

How can I get the following output?:

 "a"  "b"
  1    4
  2    5
  3    6
   

I've only managed to get them one after another but not side by side:

>jq -nc '{a: [1,2,3], b: [4,5,6]}'|jq '"a",.a[],"b", .b[]'
 "a"
  1
  2
  3
 "b"
  4
  5
  6

thanks.


Solution

  • Here is a generic solution (notice there is no mention of "a" or "b") using transpose:

    (keys_unsorted | map(tojson)),   # the header line
     ([.[]] | transpose[])
    | @tsv
    

    Invocation

    jq -r -f program.jq data.json

    Output

    "a" "b"
    1   4
    2   5
    3   6