I have the following kind of array:
{
"name": [
"Paul",
"Alex",
"John"
],
"age": [
"22",
"31",
"56"
],
"town": [
"New York",
"Los Angeles",
"Detroit"
]
}
From this I want to create new arrays with the relevant information combined into one large array called "items".
{"items": [
{
"name": "Paul",
"age": "22",
"town": "New York"
},
{
"name": "Alex",
"age": "31",
"town": "Los Angeles"
},
{
"name": "John",
"age": "56",
"town": "Detroit"
},
]}
I found out that I can do something like this to get the first string in an array but I can't find how to iterate over all strings.
jq '{items: [{ name: .name | first, age: .age | first, town: .town | first}]}'
CodePudding user response:
Here's one solution:
[.[]]
| transpose
| {items: map( {name: .[0], age: .[1], town: .[2] } )}
CodePudding user response:
Here's a solution that makes it easy to handle the key names without explicitly mentioning any of them:
def objectify($keys):
with_entries( .key |= $keys[.] );
keys_unsorted as $keys
| [.[]]
| transpose
| {items: map( objectify($keys) )}