I have the following json file that looks like this:
[
{
"data": {
"location": {
"info": [
{
"folder": {
"path": "/home/ip1"
},
"key": {
"id": "1234",
"label": "home"
}
},
{
"folder": {
"path": "/home/ip2"
},
"key": {
"id": "5678",
"label": "office"
}
},
{
"folder": {
"path": "/home/ip1"
},
"key": {
"id": "1001",
"label": "office"
}
},
{
"folder": {
"path": "/home/ip1"
},
"key": {
"id": "1002",
"label": "office"
}
}
]
}
}
}
]
Now I'd like to group and key that by "folder/path" and assign a list of id's to each of the path:
[
{
"path": "/home/ip1",
"id": [
"1234",
"1001",
"1002"
]
},
{
"path": "/home/ip2",
"id": [
"5678"
]
}
]
I try using jq group_by and map:
jq '. | group_by(.data.location.info[].folder.path) | map({ path: (.[0].path), id: [.[] | .id] })' json_file
but it returns null values.
Any help would be much appreciated! Thanks!
You almost had it right, with a few modifications on the nodes that you are applying the group_by on
jq '.[].data.location.info | group_by(.folder.path) |
map({ path: (.[0].folder.path), id: [.[].key.id] })' json
See demo on jqplay
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With