Given the following JSON structure
{
"data": [
{
"id": "000000000014444A",
"teams": [
"000000000011AE74"
]
},
{
"id": "000000000014434B",
"teams": [
"000000000011AE74",
"00000000001583CE",
"000000000010B4D7"
]
}
]
}
How can I use jq to structure the data as
[
{
"id": "000000000014444A",
"team": "000000000011AE74"
},
{
"id": "000000000014434B",
"team": "000000000011AE74"
},
{
"id": "000000000014434B",
"team": "00000000001583CE"
},
{
"id": "000000000014434B",
"team": "000000000010B4D7"
}
]
2
Answers
Take the
.data
array, andmap
each item to an object. Use.teams[]
to iterate without capturing the items in a separate array, so the output is multiplicated:Demo
There are a several ways to get the result that you want. One of them is described in @pmf’s answer.
This is another way:
How it works:
.data
extracts the propertydata
from the input (the input is an object); the value of propertydata
is an array;[]
splits the array into items; the output of.data[]
consists of multiple values, each value is one of the items of.data
; the output of.data[]
consists of two objects;|
– the next filters apply to each input value independent of other values; the input values are the values produced by.data[]
;{ id, team: .teams[] }
– the output of this filter is an object ({ ... }
) whose properties areid
andteam
;id
is a shorthand ofid: .id
; the key (id
) is the name of the property in the output object; the value (.id
) is a filter that extracts the propertyid
of each input object (the input objects have the propertiesid
andteams
);team: .teams[]
produce the propertyteam
in the output object; its value is the value of propertyteams
from the input object;teams
is an array in the input object but[]
after.team
split the value ofteams
into individual items; the expression.teams[]
produce multiple output values from one input value; it produces one result for the object withid
equal to"000000000014444A"
and three results for the object withid
equal to"000000000014434B"
.All in all, the expression
.data[] | { id, team: .teams[] }
produce four results as output.The outer
[
and]
wrap the results produced by the enclosed pipeline into an array. The array (which is the output of the entire program) contains the four items generated by the inner expression. It is the output that you expect.See it on the jq playground.