2

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}, ]

2
  • What did you try for yourself? Pure JSON doesn't take single quotes for key fields Commented May 14, 2020 at 7:44
  • transpose results in an error: Cannot index object with number forcing string keys with to_entries or even map(to_entries) didnt lead to anything usefull yet map will only itterate one column and not result in any key access to the second column Commented May 14, 2020 at 7:49

3 Answers 3

1

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. there are many answers that lead to the same result. accepting this one as it was the first.
1

Use transpose builtin:

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

1 Comment

Thank you. there are many answers that lead to the same result. I've accepted the first one, though i like this approach!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.