gpt4 book ai didi

python - 如何获取 JSON 字典列表中的特定键

转载 作者:行者123 更新时间:2023-12-03 07:46:55 26 4
gpt4 key购买 nike

我正在尝试通过 list_stacks() 获取最后一个删除的名为 BastionInfraStack 的堆栈(最近的堆栈)的 StackIdlist_stacks() 命令返回以下内容:

{
"StackSummaries": [
{
"StackId": "arn:aws:cloudformation:us-east-2:111111111:stack/Dev-BastionInfraStack/34deb540-9c2f-11ed-90a7-022b01b65a64",
"StackName": "Dev-BastionInfraStack",
"CreationTime": "2023-01-24T21:36:48.468000+00:00",
"LastUpdatedTime": "2023-01-24T21:37:26.782000+00:00",
"DeletionTime": "2023-01-24T22:19:03.403000+00:00",
"StackStatus": "DELETE_COMPLETE",
"DriftInformation": {
"StackDriftStatus": "NOT_CHECKED"
}
},
{
"StackId": "arn:aws:cloudformation:us-east-2:111111111:stack/TestInfraStack/cf6d58d0-9b8c-11ed-a58b-02446413ef88",
"StackName": "Dev-BastionInfraStack",
"CreationTime": "2023-01-24T16:53:12.552000+00:00",
"LastUpdatedTime": "2023-01-24T20:45:36.941000+00:00",
"DeletionTime": "2023-01-24T21:15:49.673000+00:00",
"StackStatus": "DELETE_COMPLETE",
"DriftInformation": {
"StackDriftStatus": "NOT_CHECKED"
}
},
{
"StackId": "arn:aws:cloudformation:us-east-2:111111111:stack/Dev-BastionInfraStack/54bcf7c0-9b51-11ed-bae1-02f106ea059a",
"StackName": "Dev-BastionInfraStack",
"CreationTime": "2023-01-23T19:08:33.666000+00:00",
"LastUpdatedTime": "2023-01-23T19:09:06.759000+00:00",
"DeletionTime": "2023-01-23T20:59:59.677000+00:00",
"StackStatus": "DELETE_COMPLETE",
"DriftInformation": {
"StackDriftStatus": "NOT_CHECKED"
}
}
]
}

目前,我获取堆栈列表的方式如下:

      deleted_stacks = cfn.list_stacks(
StackStatusFilter=['DELETE_COMPLETE']
)

如何遍历该对象列表,检查我需要的堆栈是否具有名称 BastionInfraStack (可能使用正则表达式或通配符)并获取 StackId 并分配它到一个变量以便稍后在另一个函数中使用?

例如在这种情况下我想得到StackId arn:aws:cloudformation:us-east-2:111111111:stack/Dev-BastionInfraStack/34deb540-9c2f-11ed-90a7-022b01b65a64

最佳答案

您必须循环浏览列表并选择符合您条件的元素。

Python 的编写方式是

 mystacks=[d['StackId'] for d in deleted_stacks['StackSummaries'] if d['StackName']=="Dev-BastionInfraStack"]

如果您只想查找“BastionInfraStack”,请更改查找子字符串的条件

关于python - 如何获取 JSON 字典列表中的特定键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75228261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com