【问题标题】:recurse through json in python在python中通过json递归
【发布时间】:2015-12-23 14:19:00
【问题描述】:

我有一个示例 json:

我想使用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

【问题讨论】:

  • 下次请贴文字,不要发图片
  • 这是一个巨大的 json,不希望它占据整个空间,所以只使用了图片。我知道我可以修剪它。会的。

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


【解决方案1】:
for asg in resources:

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

for asg in resources.values():

【讨论】:

  • 我会做 keys() 而不是 values() 所以你可以选择重现符合你标准的键的内容。
  • @rajesh.kanakabandi 和帖子的所有者 - 看看编辑
  • 你不需要内部 for 循环。当你想访问 MaxSize 时。
【解决方案2】:
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"]

试试这个。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-01-28
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多