请你帮忙建议:) 我有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 :(得分: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
个例外。