简体   繁体   English

Python 解析嵌套的 json 数据并返回每个索引

[英]Python parsing nested json data and returning each index

I'm trying to parse a json file that contains logs from Linux system.我正在尝试解析包含来自 Linux 系统的日志的 json 文件。 I am trying to iterate over each key and print the values appended to them in order automatically.我正在尝试遍历每个键并自动按顺序打印附加到它们的值。 I will post the code I have now and some sample data.我将发布我现在拥有的代码和一些示例数据。

JSON File: JSON 文件:

{
    "centos8-test": {
        "time": [
            "20:59:55",
            "20:59:55",
            "22:35:00",
            "22:35:10"
        ],
        "uid": [
            "uid=0",
            "uid=0",
            "uid=0",
            "uid=0"
        ],
        "hex": [
            "746573740A",
            "746573740A",
            "6861636B65640A",
            "6861636B65640A"
        ]
    },
    "ubuntu-test": {
        "time": [
            "21:00:43",
            "21:00:43"
        ],
        "uid": [
            "uid=0",
            "uid=0"
        ],
        "hex": [
            "746573740A",
            "746573740A"
        ]
    }
}

Sample Python Code:样品 Python 代码:

def read_json(self, json_file):
        with open(json_file, 'r', encoding='utf-8') as fp:
            data = json.load(fp)
            for key, value in data.items():
                for sub_key, sub_val in value.items():
                    print(data[key][sub_key])

Python JSON Output: Python JSON Output:

['20:59:55', '20:59:55', '22:35:00', '22:35:10']
['uid=0', 'uid=0', 'uid=0', 'uid=0']
['746573740A', '746573740A', '6861636B65640A', '6861636B65640A']
['21:00:43', '21:00:43']
['uid=0', 'uid=0']
['746573740A', '746573740A']

Ideally, I would like some output like this:理想情况下,我想要一些 output 像这样:

centos8-test, '20:59:55', 'uid=0', 746573740A

and continue to print each row.并继续打印每一行。

NOTE: I program for fun so I am not the best at this.注意:我编程是为了好玩,所以我不是最擅长的。

You can write something like this:你可以这样写:

def read_json(json_file):
    with open(json_file, 'r', encoding='utf-8') as fp:
        data = json.load(fp)
        for key, value in data.items():
            for time, uid, hex in zip(value['time'], value['uid'], value['hex']):
                print(', '.join([key, time, uid, hex]))

Output: Output:

centos8-test, 20:59:55, uid=0, 746573740A
centos8-test, 20:59:55, uid=0, 746573740A
centos8-test, 22:35:00, uid=0, 6861636B65640A
centos8-test, 22:35:10, uid=0, 6861636B65640A
ubuntu-test, 21:00:43, uid=0, 746573740A
ubuntu-test, 21:00:43, uid=0, 746573740A

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM