gpt4 book ai didi

python - 在python中通过json递归

转载 作者:太空宇宙 更新时间:2023-11-04 10:17:31 25 4
gpt4 key购买 nike

我有一个示例 json:

enter image description here

我想使用 python 的 json 模块并递归查找“pevcwebasg”中的“MaxSize”。有以下代码:

导入json

param_file_handle = json.load(open("sample.json"))
print param_file_handle['Resources']['pevcwebasg']['Type']
resources = param_file_handle['Resources']
for asg in resources:
print asg["Type"]

它的输出是:

> AWS::AutoScaling::AutoScalingGroup Traceback (most recent call last): 
> File "test.py", line 8, in <module>
> print asg['Type'] TypeError: string indices must be integers

我没有得到的是这一行“print param_file_handle['Resources']['pevcwebasg']['Type']”工作正常并让我得到输出但是当我递归并尝试找到asg [“Type” ], 它失败。有什么更好的方法吗?我需要遍历树并找到值。

编辑 1:

当我递归遍历值时,我遇到了错误。

param_file_handle = json.load(open("sample.json"))
resources = param_file_handle['Resources']
for asg in resources.values():
if asg["Type"] == "AWS::AutoScaling::AutoScalingGroup":
for values in asg['Properties']:
print values["MaxSize"]

错误:

Traceback (most recent call last):
File "test.py", line 9, in <module>
print values["MaxSize"]
TypeError: string indices must be integers

最佳答案

for asg in resources:

这遍历 resources 的键,而不是值。尝试:

for asg in resources.values():

关于python - 在python中通过json递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34437652/

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