2015-07-20 74 views
0

請您與指教:)
幫助我有一個像JSON文件:蟒蛇:篩選複雜的JSON文件

{ 
content: { 
hostname01: { 
active_checks_enabled: "1", 
current_attempt: "1", 
plugin_output: "SSH OK", 
services: { 
    monitoring: { 
     active_checks_enabled: "0", 
     current_attempt: "1", 
     current_state: "0", 
     downtimes: { }, 
     plugin_output: "PASV MONITORNG OK", 
     last_check: "1437382990", 
     problem_has_been_acknowledged: "0", 
     } 
}, 
comments: { }, 
last_notification: "0", 
max_attempts: "5" 
}, 

我怎麼能格式化這個大的文件,所以我只有像對象:

{ 
hostname01:{ 
    monitoring: { 
    current_state: "1" 
    } 
} 
} 

有兩種可能的current_states:0,1. 預先感謝您!

+0

您的JSON文件無效 - 缺少兩個大括號,並且在有效的JSON'keys'中需要包含在''雙引號'中' – Finwood

+0

考慮設置一個接受的答案,如果它對您的問題有幫助。 – adrianus

回答

0

隨着valid JSON輸入,就可以使用該模塊json(我從一個文件中猜測,在這裏我只把它放到代碼)讀取數據:

import json 

json_data = """ 
{ 
    "content": { 
     "hostname01": { 
      "active_checks_enabled": "1", 
      "current_attempt": "1", 
      "plugin_output": "SSH OK", 
      "services": { 
       "monitoring": { 
        "active_checks_enabled": "0", 
        "current_attempt": "1", 
        "current_state": "0", 
        "downtimes": {}, 
        "plugin_output": "PASV MONITORNG OK", 
        "last_check": "1437382990", 
        "problem_has_been_acknowledged": "0" 
       } 
      }, 
      "comments": {}, 
      "last_notification": "0", 
      "max_attempts": "5" 
     } 
    } 
} 
""" 

data = json.loads(json_data) 

然後通過主機名環路和保存值從current_state

reduced_data = {} 
for hostname in data["content"]: 
    current_state = data["content"][hostname]["services"]["monitoring"]["current_state"] 
    reduced_data[hostname] = {"monitoring": {"current_state": current_state}} 

print json.dumps(reduced_data, sort_keys=True, indent=4, separators=(',', ': ')) 

輸出:

{ 
    "hostname01": { 
     "monitoring": { 
      "current_state": "0" 
     } 
    } 
} 

你必須確保所有hostname節點具有相同的結構或者捕獲並處理KeyError例外。

+0

非常感謝!!!! :)))) 有用!巨大的謝謝你一個時間 – Iana

+0

不客氣!考慮提升或設置爲接受的答案,如果它幫助你:-) – adrianus