1

是否可以对 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'方法,但我想回到按原样格式化的整个文档的上下文中。

4

1 回答 1

3

对于jq处理器来说,这是一项很好的工作:

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

  • |=-更新语句/动作(更新所选项目)


输出:

{
  "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
于 2017-10-13T12:59:19.097 回答