python - 在python中通过json递归

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

我有一个示例 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/

相关文章:

python - 通过ansible playbook在python终端中运行命令

python - 适用于 python2.7 的 Google 表格 API --> "Invalid JSON payload. Root element must be a message"

javascript - 如何正确路由到 Express 中的 JSON 条目

Python 从 JSON 到 JSONL 的转换

python - 使用 Pyside 从主窗口打开子对话窗口

python - 为什么手动字符串反转比 Python 2.7 中的切片反转更糟糕? Slice 中使用的算法是什么?

python-2.7 - 为 python 安装 adwords Api - 'Given yaml file, %s, could not be opened.' % 路径)'

python - Tkinter 多帧调整大小

Python 十六进制编辑器/编辑组件

python - 在 Python 中使用 Apps Script Execution API 时出现 404 错误