Is it possible to sort a particular array of a json document and output the entire document with the sorted content otherwise untouched?
For example, if I have something like this:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "BLAHBLAHBLAH",
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::346654243625:root",
"arn:aws:iam::984895836564:root",
"arn:aws:iam::636877599363:root",
"arn:aws:iam::577836285792:root",
"arn:aws:iam::836666644595:root",
"arn:aws:iam::652379234777:root",
"arn:aws:iam::339659563489:root",
"arn:aws:iam::293576423935:root",
"arn:aws:iam::682354689262:root",
"arn:aws:iam::349855857558:root",
"arn:aws:iam::398259495958:root",
"arn:aws:iam::735277384553:root"
]
},
"Action": "s3:*",
"Resource": [
"arn:aws:s3:::blah-blah-blah",
"arn:aws:s3:::blah-blah-blah/*"
]
}
]
}
I'd like to get back this:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "BLAHBLAHBLAH",
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::293576423935:root",
"arn:aws:iam::339659563489:root",
"arn:aws:iam::346654243625:root",
"arn:aws:iam::349855857558:root",
"arn:aws:iam::398259495958:root",
"arn:aws:iam::577836285792:root",
"arn:aws:iam::636877599363:root",
"arn:aws:iam::652379234777:root",
"arn:aws:iam::682354689262:root",
"arn:aws:iam::735277384553:root",
"arn:aws:iam::836666644595:root",
"arn:aws:iam::984895836564:root"
]
},
"Action": "s3:*",
"Resource": [
"arn:aws:s3:::blah-blah-blah",
"arn:aws:s3:::blah-blah-blah/*"
]
}
]
}
I have seen sorting examples using jq
and JMESPath
but only ever seen them output the section being sorted and not the entire document with the sorted section. Looking for guidance in the matter and would be happy with any working solution.
This is what I have used to sort the array | jq '.Statement[].Principal.AWS|sort'
which works, but I'd like to get back into the context of the entire document formatted as it was.
It's a good job for jq processor:
jq '.Statement[0].Principal.AWS |= sort' file
.Statement[0].Principal.AWS
- selected item
|=
- update statement/action (to update the selected item)
The output:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "BLAHBLAHBLAH",
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::293576423935:root",
"arn:aws:iam::339659563489:root",
"arn:aws:iam::346654243625:root",
"arn:aws:iam::349855857558:root",
"arn:aws:iam::398259495958:root",
"arn:aws:iam::577836285792:root",
"arn:aws:iam::636877599363:root",
"arn:aws:iam::652379234777:root",
"arn:aws:iam::682354689262:root",
"arn:aws:iam::735277384553:root",
"arn:aws:iam::836666644595:root",
"arn:aws:iam::984895836564:root"
]
},
"Action": "s3:*",
"Resource": [
"arn:aws:s3:::blah-blah-blah",
"arn:aws:s3:::blah-blah-blah/*"
]
}
]
}
To sort multiple arrays use:
jq '.Statement[].Principal.AWS |= sort' file