[英]python: filter complex json file
您能幫忙請教一下:)
我有像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。預先謝謝!
使用有效的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
異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.