使用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 theStatementarray|=: 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 theSidandEffectfields as-is, and replaces thePrincipalwith 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
相关产品推荐
相关产品推荐

