Home > Enterprise >  Python parsing nested json data and returning each index
Python parsing nested json data and returning each index

Time:08-02

I'm trying to parse a json file that contains logs from Linux system. 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:

{
    "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:

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:

['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:

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.

CodePudding user response:

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:

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
  • Related