通过python中的json递归

时间:2015-12-23 14:19:00

标签: python json python-2.7 python-3.x

我有一个样本json:

enter image description here

我想使用python的json模块并通过recurse来查找“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

3 个答案:

答案 0 :(得分:3)

for asg in resources:

这会迭代resources的键,而不是值。尝试:

for asg in resources.values():

答案 1 :(得分: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":
          print asg["Properties"]["MaxSize"]

试试这个。

答案 2 :(得分:0)

你打破了雇佣关系,错过了&#34; pevcwebasg&#34;

resources = param_file_handle['Resources']['pevcwebasg']
for asg in resources:
     print asg["Type"]