2015-12-23 126 views
1

JSON我有一個樣品JSON:遞歸通過蟒蛇

enter image description here

我想使用Python的json模塊,並通過遞歸找到「最大範圍」,在「pevcwebasg」。有下面的代碼:

進口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 

什麼我不明白是該行「打印param_file_handle [ '資源'] ['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 
+0

下一次,請粘貼文本,而不是張貼圖片 –

+0

這是一個巨大的json,不希望它佔用整個空間,所以只是使用圖片。我知道我可以修剪它。會做。 – Scooby

回答

3
for asg in resources: 

此遍歷的resources的鑰匙,而不是值。嘗試:

for asg in resources.values(): 
+0

完美,謝謝。 zzz我的壞! – Scooby

+0

我會做鍵()而不是values(),所以你可以選擇重現符合你的標準的鍵的內容。 –

+0

@ rajesh.kanakabandi和帖子的所有者 - 看看編輯 – Scooby

0

你分手hirerchy,錯過了 「pevcwebasg」

resources = param_file_handle['Resources']['pevcwebasg'] 
for asg in resources: 
    print 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": 
      print asg["Properties"]["MaxSize"] 

嘗試。