python:filter复杂json-fi

2024-05-23 20:24:34 发布

您现在位置:Python中文网/ 问答频道 /正文

你能帮我提个建议吗:)
我有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"
    }
}
}

有两种可能的当前状态:0、1。 提前谢谢!你知道吗


Tags: 文件jsonoutputenabledokcurrentplugin建议
1条回答
网友
1楼 · 发布于 2024-05-23 20:24:34

使用valid 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异常。你知道吗

相关问题 更多 >