vendredi 27 août 2021

Adding a condition in recursive function to read out specific key and its value inside a nested json file

I have been working on a project on the in which I am trying to get a blockdevice inside a server that acts as a backup disk and has to be replaced every week atleast once.

.json file that shows whats mounted inside the server: https://pastebin.com/hmjv81nS

I have some code that includes a recursive function to list out the names and the sizes of the disks inside the server:

import json

with open('path to json file') as file:
    data = json.load(file)

def process_data(data_list, names, sizes):
    for d in data_list:
        names.append(d['name'])
        sizes.append(d['size'])
        if 'children' in d:
            process_data(d['children'],  names, sizes)
    return names, sizes
    
print(process_data(data['blockdevices'], [], []))
>>> (['sda', 'sda1', 'md0', 'sda2', 'sda5', 'md1', 'sda6', 'md2', 'sda7', 'md3', 'sdb', 'sdb1', 'md0', 'sdb2', 'sdb5', 'md1', 'sdb6', 'md2', 'sdb7', 'md3', 'sdc', 'sdc1', 'DATA', 'sdd', 'sdd1', 'DATA2', 'sde', 'sde1'], ['931,5G', '18,6G', '18,6G', '1K', '9,3G', '9,3G', '18,6G', '18,6G', '885G', '884,8G', '931,5G', '18,6G', '18,6G', '1K', '9,3G', '9,3G', '18,6G', '18,6G', '885G', '884,8G', '5,5T', '5,5T', '5,5T', '3,7T', '3,7T', '3,7T', '9,1T', '9,1T'])

Now I want to add a condition to find out which of the disks is the backup disk. I know for a fact that the backup disk is >5.0T in size, that there is only ONE another dict under the list of key "children" and inside the second dict there is not another "children" that lists another dict.

My approach was to find out inside the function that if there is 2 children inside the list of the disk then the disk will be ignored and not printed out.

The result should be a print of disk "sde" hence it has only a single dict under its list "children" and not another "children" inside that dict.

Hope you understand my concern it has been a struggle to find out a way.

Aucun commentaire:

Enregistrer un commentaire