convert column arrays to array of row objects

Viewed 567

i have a json file representing a table with two columns.

the Column values are in an array

{ 'columnA':[1,2,3], 'columnB':[6,7,8] }

i need to convert it to an array of rows:

[ {'columnA':1, 'columnB':6}, {'columnA':2, 'columnB':7}, {'columnA':3, 'columnB':8}, ]

3 Answers

Here is one solution:

[range(0; .columnA|length) as $i
 | {columnA: .columnA[$i], columnB: .columnB[$i]}]

And here's another that is keyname-neutral and should work for any number of "columns":

def objectify($template):
  . as $in
  | ($template|keys_unsorted) as $k
  | reduce range(0; $k|length) as $i (null; . + {($k[$i]): $in[$i]});

. as $in
| [.[]]
| transpose
| map(objectify($in))

Use transpose builtin:

[ [{columnA: .columnA[]}],
  [{columnB: .columnB[]}]
] | transpose | map(add)

i figured it out:

[.columnA,.columnB] | transpose | map({"columnA":.[0], "columnB": .[1]})

  1. Convert to array of arrays
  2. transpose
  3. convert back to objects
Related