当前位置: 动力学知识库 > 问答 > 编程问答 >

python: filter complex json file

问题描述:

Could you please help with advise :)

I have json file like:

{

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"

},

how can I format this big file so I only have object like:

{

hostname01:{

monitoring: {

current_state: "1"

}

}

}

There two possible current_states: 0, 1.

Thank you in advance!

网友答案:

With valid JSON input, you can read the data using the module json (I guess from a file, here I'll just put it into the code):

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)

Then loop through the hostnames and save the value from 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=(',', ': '))

Output:

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

You'll have to assure that all hostname nodes have the same structure or else catch and handle KeyError exceptions.

分享给朋友:
您可能感兴趣的文章:
随机阅读: