使用JQ添加并修改JSON对象



示例json输入:

 {  
"Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowFullAccess",
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::XXXX:user/test",
          "arn:aws:iam::XXXX:root"
        ]
      },
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::test-dev-cognito-settings-us-west-2/*"
      ],
      "Condition": {
        "StringNotLike": {
          "aws:userId": [
            "AZASDASDSADA"
          ]
        }
      }
    }
  ]
}

预期的JSON输出:

  {  
"Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowFullAccess",
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::XXXX:user/test",
          "arn:aws:iam::XXXX:root"
        ]
      },
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::test-dev-cognito-settings-us-west-2/*"
      ],
      "Condition": {
        "StringNotLike": {
          "aws:userId": [
            "AZALEA",
            "Hello"
          ]
        }
      }
},
{
  "Sid": "AllowForSpecificLambda_jdtest",
  "Effect": "Allow",
  "Principal": {
    "AWS": "AROAIBA5TVJCIN3OCE2YI"
  },
  "Action": "s3:Get*",
  "Resource": [
    "arn:aws:s3:::oppscience-dev-cognito-settings-us-west-2",
    "arn:aws:s3:::oppscience-dev-cognito-settings-us-west-2/*"
  ],
  "Condition": {
    "StringNotLike": {
      "aws:userId": [
        "AZA"
      ]
    }
  }
 ]
}

赦免我,我在JSON标签中犯了一些语法错误。我想要的只是我要添加新对象 修改现有对象的语句数组对象。我正在使用JQ添加新的JSON对象。以下是我的代码段,它可以正常工作。

jq '.Statement[.Statement| length] |= . + {
 "Sid": "AllowForSpecificLambda",
 "Effect": "Allow",
 "Principal": {
    "AWS": [
        "arn:aws:iam::XXXXXXXXXX:role/lambda_allow_pretoken_generation"
    ]
   },
 "Action": "s3:Get*","Resource": [
        "arn:aws:s3:::test-XXXX-cognito-settings-'$region'"
        ]}' test.json > test-1.json

我使用以下代码段。

jq '.Statement[] 
| select(.Sid == "Test") 
.Condition.StringNotLike."aws:userId"[.Condition.StringNotLike."aws:userId"| length] 
|= . + "Hello"' test.json

我该如何在单个命令中完成这两件事?

谢谢

任务的描述似乎与给定的输入和输出不符,但是以下内容应该使您前进,因为它说明了您似乎丢失的作品 - 是,要结合两个操作,只需将它们组合到管道中(即使用|(。

另一个关键点是建议将参数(例如本情况下的$region(作为JQ程序的参数。

program.jq

  .Statement += [ 
    {
     "Sid": "AllowForSpecificLambda",
     "Effect": "Allow",
     "Principal": {
        "AWS": [
            "arn:aws:iam::XXXXXXXXXX:role/lambda_allow_pretoken_generation"
        ]
       },
     "Action": "s3:Get*","Resource": [
            "arn:aws:s3:::test-XXXX-cognito-settings-" + $region
            ]}
        ]
  | .Statement[0].Condition.StringNotLike."aws:userId" += ["Hello"]

调用

假设您希望$region具有一定的价值,例如"区域":

jq --arg region REGION -f program.jq test.json

最新更新