输出包含排序内容的整个 JSON 文档

Output entire JSON document with sorted content

是否可以对 json 文档的特定数组进行排序并输出整个文档以及排序后的内容?

例如,如果我有这样的东西:

{
  "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/*"
      ]
    }
  ]
}

我想取回这个:

{
  "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/*"
      ]
    }
  ]
}

我看过使用 jqJMESPath 的排序示例,但只见过它们输出正在排序的部分,而不是包含已排序部分的整个文档。在此事上寻求指导,并对任何可行的解决方案感到满意。

这是我用来对数组 | jq '.Statement[].Principal.AWS|sort' 进行排序的方法,但我想回到整个文档的上下文中。

jq 处理器做得很好:

jq '.Statement[0].Principal.AWS |= sort' file
  • .Statement[0].Principal.AWS - 已选项目

  • |= - update statement/action(更新所选项目)


输出:

{
  "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/*"
      ]
    }
  ]
}

要对多个数组进行排序,请使用:

jq '.Statement[].Principal.AWS |= sort' file