在python中通过json递归

2024-05-16 00:04:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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\u file\u 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

Tags: injsonforparamtypeloadfilehandle
3条回答

你打破了雇佣关系,错过了“pevcwebasg”

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

试试这个。你知道吗

for asg in resources:

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

for asg in resources.values():

相关问题 更多 >