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?
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.
Using map
makes for quite a tidy answer:
group_by(.clusterName)
| map( {clusterName: .[0].clusterName,
buckets: map( {name} ) } )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.