You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jq添加并修改JSON对象:基于指定示例完成转换

Using jq to Transform Your JSON Policy

Hey there! Let's walk through how to use jq to tweak your JSON into the exact structure you need. Here's everything you need to know:

Sample Input & Expected Output

First, let's recap what we're starting with and where we want to end up.

Sample JSON Input

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

Expected JSON Output

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowFullAccess",
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aw..."
        ]
      }
    }
  ]
}

The jq Command

This one-liner will do all the heavy lifting:

jq '.Statement[0] |= {Sid, Effect, Principal: {AWS: ["arn:aw..."]}}' input.json

Let's Break It Down

  • .Statement[0]: Targets the first (and only) object inside the Statement array
  • |=: Tells jq "take the thing I just selected, and modify it with the following logic"
  • {Sid, Effect, Principal: {AWS: ["arn:aw..."]}}: Reconstructs the object to only keep the Sid and Effect fields as-is, and replaces the Principal with your desired truncated AWS ARN array.

Handling Multiple Statement Entries

If you ever have more than one object in the Statement array and want to apply this change to all of them, just swap out the [0] for [] to iterate over every entry:

jq '.Statement[] |= {Sid, Effect, Principal: {AWS: ["arn:aw..."]}}' input.json

Testing It Out

Run the command against your input JSON file, and you'll get exactly the output you're looking for. Easy peasy!

内容的提问来源于stack exchange,提问作者Jayesh Dhandha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:15:57