Reputation: 26281
Suppose I have the following JSON array:
[
[
{ "value": "first_name" },
{ "value": "last_name" },
{ "value": "age" }
],
[
{ "value": "John" },
{ "value": "Johnson" },
{ "value": 27 }
],
[
{ "value": "Martin" },
{ "value": "Martinson" },
{ "value": 18 }
]
]
You can think of this JSON as a different view for:
| first_name | last_name | age |
|------------|-----------|-----|
| John | Johnson | 27 |
| Martin | Martinson | 18 |
The first item of the array always represents the "columns", while the other items are the rows.
I'd like to transform the above JSON into something more readable, i.e. getting rid of the first item altogether, merging all the separated objects and also udpating the field name accordingly:
[
{
"first_name": "John",
"last_name": "Johnson",
"age": 27
},
{
"first_name": "Martin",
"last_name": "Martinson",
"age": 18
}
]
Ideally, I'd like to achieve this with a CLI tool such as jq - is this possible?
Upvotes: 0
Views: 217
Reputation: 24802
The following jq
invocation works for your sample input :
.[0] as $header | .[1:] | map( { ($header[0].value) : .[0].value, ($header[1].value) : .[1].value, ($header[2].value) : .[2].value } )
It extracts the header then iterate over the rest of the list, creating an object with keys extracted from the header and values from the current element.
You can try it here.
It only handles inputs with a specific amount of columns though, while I think it would be possible to generically link the values of the first item with those of the other items.
This is exactly what I was looking for. I've enhanced your example with this version that is not coupled to the # of columns:
[.[0][].value] as $cols | [.[1:][] | to_entries] | map(map({($cols[.key]): .value.value}) | add)
Upvotes: 1
Reputation: 134841
Here's another way you can construct the desired results.
(.[0] | map({key:.value})) as $keys | [.[1:][] | [$keys,.] | transpose | map(add) | from_entries]
You can take advantage of from_entries
here treating the header and rows as sets of keys and values. You just need to manipulate the values to be paired up with their corresponding keys.
Upvotes: 1