如何在shell脚本中读取awscli响应

时间:2019-02-19 17:08:32

标签: json shell amazon-dynamodb aws-cli

想从AWS CLI响应中读取“项目”。并想在“项目”上写“ for循环”。但是我无法在shell脚本中执行。 AWS cli命令的输出格式为JSON格式。

Sh代码:

[ ~]$ response_scan=`aws dynamodb scan --table-name recovery-plan --max-items 10 --attributes-to-get '["job_id", "job_type", "launch_category"]'`


[ ~]$ echo $response_scan
{ 
   "Count": 166, 
   "Items": [ 
        { "launch_category": { "S": "TOT" }, "job_type": { "S": "TEST" }, "job_id": { "S": "39504214122e" } }, 
        { "job_type": { "S": "TEST" }, "job_id": { "S": "8c48-914d0aa2a186" } },  
         { "job_type": { "S": "TEST" }, "job_id": { "S": "cbd07892491d" } }, 
         { "job_type": { "S": "TEST1" }, "job_id": { "S": "7afef48b0283" } },  
         { "job_type": { "S": "TEST" }, "job_id": { "S": "7d678fab68e1" } } 
     ], 
    "NextToken": "eyJFasasaseGNsdXasasaslX2Ftb3VudCasasI6IDEwfQ==",
     "ScannedCount": 166, 
     "ConsumedCapacity": null 
}

任何人都可以帮助我遍历response_scan [“ Items”]吗?

我正在做什么: 我要添加字段-launch_category到没有此字段的项目/行。 launch_category的值对于TEST为TOT,对于TEST1为TOT1

2 个答案:

答案 0 :(得分:1)

response_scan=$(aws dynamodb scan --table-name recovery-plan --max-items 10 --attributes-to-get '["job_id", "job_type", "launch_category"]' --query Items[].job_type.S --output text )

或者您可以使用jq解析json-https://stedolan.github.io/jq/

答案 1 :(得分:0)

上述答案仍然有效,建议根据 AWS 文档使用 --projection-expression 而不是 --attribute-to-get 在此处更新。

<块引用>

--attributes-to-get(列表)

<块引用>

这是一个遗留参数。请改用 ProjectionExpression。有关更多信息,请参阅 Amazon DynamoDB 开发人员指南 中的 AttributesToGet。

response_scan=$(aws dynamodb scan 
--table-name recovery-plan 
--max-items 10 
--projection-expression "job_id, job_type,launch_category" 
--query Items[].job_type.S --output text 
)

AttributesToGet