Reputation: 363
Here's the json document
[
{"name": "bucket1","clusterName":"cluster1"},
{"name": "bucket2","clusterName":"cluster1"},
{"name": "bucket3","clusterName":"cluster2"},
{"name": "bucket4","clusterName":"cluster2"}
]
And I want to convert it to
[
{"clusterName": "cluster1", buckets:[{"name": "bucket1"}, {"name": "bucket2"}]},
{"clusterName": "cluster2", buckets:[{"name": "bucket1"}, {"name": "bucket2"}]},
]
How do I do that in jq?
Upvotes: 5
Views: 2977
Reputation: 2388
Using map
and based on peak's answer, I needed all the bucket names in an array:
jq 'group_by(.clusterName) | map( { clusterName : .[0].clusterName, buckets: [ .[].name ] } )'
gives:
[
{
"clusterName": "cluster1",
"buckets": [
"bucket1",
"bucket2"
]
},
{
"clusterName": "cluster2",
"buckets": [
"bucket3",
"bucket4"
]
}
]
Upvotes: 0
Reputation: 116670
Using map
makes for quite a tidy answer:
group_by(.clusterName)
| map( {clusterName: .[0].clusterName,
buckets: map( {name} ) } )
Upvotes: 1
Reputation: 870
cat doc.json | jq '[group_by(.clusterName)[] | { clusterName: .[0].clusterName, "buckets": [.[] | { name: .name } ]}]'
Should do what you want. Now with an array around as well.
Upvotes: 3