I want to use JQ to sort each ddd
-json-array by looking at its values in the .fff.ggg.hhh.iii
-property.
So for example look at this json:
{
"aaa-1": {
"ddd": [
{"fff": {"ggg": {"hhh": {"iii": "100"}}}},
{"fff": {"ggg": {"hhh": {"iii": "1"}}}},
{"fff": {"ggg": {"hhh": {"iii": "10"}}}}
]
},
"aaa-2": {
"ddd": [
{"fff": {"ggg": {"hhh": {"iii": "1000"}}}},
{"fff": {"ggg": {"hhh": {"iii": "333"}}}}
]
},
"aaa-3": {
"ddd": [
{"fff": {"ggg": {"hhh": {"iii": "77"}}}},
{"fff": {"ggg": {"hhh": {"iii": "88"}}}},
{"fff": {"ggg": {"hhh": {"iii": "5555"}}}},
{"fff": {"ggg": {"hhh": {"iii": "1"}}}}
]
}
...
"aaa-n": {
"ddd": [
{"fff": {"ggg": {"hhh": {"iii": "989898"}}}},
...
{"fff": {"ggg": {"hhh": {"iii": "1"}}}},
]
}
}
What I want to end up with should look like this:
{
"aaa-1": {
"ddd": [
{"fff": {"ggg": {"hhh": {"iii": "1"}}}},
{"fff": {"ggg": {"hhh": {"iii": "10"}}}}
{"fff": {"ggg": {"hhh": {"iii": "100"}}}}
]
},
"aaa-2": {
"ddd": [
{"fff": {"ggg": {"hhh": {"iii": "333"}}}},
{"fff": {"ggg": {"hhh": {"iii": "1000"}}}}
]
},
"aaa-3": {
"ddd": [
{"fff": {"ggg": {"hhh": {"iii": "1"}}}},
{"fff": {"ggg": {"hhh": {"iii": "77"}}}},
{"fff": {"ggg": {"hhh": {"iii": "88"}}}},
{"fff": {"ggg": {"hhh": {"iii": "5555"}}}}
]
}
...
"aaa-n": {
"ddd": [
{"fff": {"ggg": {"hhh": {"iii": "4"}}}},
...
{"fff": {"ggg": {"hhh": {"iii": "989898"}}}}
]
}
}
I have tried various combinations and variants of these answers, but I could not come up with a solution:
- https://stackoverflow.com/a/58665725/504060
- https://stackoverflow.com/a/30332672/504060
- https://stackoverflow.com/a/51125483/504060
I hope I could at least describe the problem in a meaningful fashion.
Can someone help me?
CodePudding user response:
Update |=
each field's array using sort_by
, and convert to numbers using tonumber
:
jq '.[].ddd |= sort_by(.fff.ggg.hhh.iii | tonumber)'
{
"aaa-1": {
"ddd": [
{"fff":{"ggg":{"hhh":{"iii":"1"}}}},
{"fff":{"ggg":{"hhh":{"iii":"10"}}}},
{"fff":{"ggg":{"hhh":{"iii":"100"}}}}
]
},
"aaa-2": {
"ddd": [
{"fff":{"ggg":{"hhh":{"iii":"333"}}}},
{"fff":{"ggg":{"hhh":{"iii":"1000"}}}}
]
},
"aaa-3": {
"ddd": [
{"fff":{"ggg":{"hhh":{"iii":"1"}}}},
{"fff":{"ggg":{"hhh":{"iii":"77"}}}},
{"fff":{"ggg":{"hhh":{"iii":"88"}}}},
{"fff":{"ggg":{"hhh":{"iii":"5555"}}}}
]
},
"aaa-n": {
"ddd": [
{"fff":{"ggg":{"hhh":{"iii":"1"}}}},
{"fff":{"ggg":{"hhh":{"iii":"989898"}}}}
]
}
}