Home > other >  Adding info on JSON file
Adding info on JSON file

Time:11-17

i need to see if someone has any idea of adding information on a json file, my end is getting all package versions on JSON to deploy it on webpage:

version.json (i'd love to add all info in these keys)

[
    {
        "software": "",
        "version": ""
    },
    {
        "software": "",
        "version": ""
    }
]

main.py

import subprocess as sp, re, json

data = ["node", "python3", "ansible", "perl"] ## Could be more of this
data_dict = {}

pattern = r'[a-zA-Z]'
p_perl = r'\((.*?)\)'

        
def getData():
    for i in data:
        if i == "perl":
            v1 = sp.run(["perl", "--version"], check=True, stdout=sp.PIPE)
            v1_decode = v1.stdout.decode('utf-8')
            v1_name = re.search(p_perl, v1_decode).group(1)
            v1_name2 = re.sub(pattern, '',v1_name)
            v1_strip = v1_name2.strip()
            data_dict[i] = v1_strip
            #print(sw1, v1_strip)

        else:
            v2 = sp.run([i, "--version"], check=True, stdout=sp.PIPE)
            v2_args = sp.run(['head', '-n1'],input=v2.stdout, stdout=sp.PIPE)
            v2_decode = v2_args.stdout.decode('utf-8')
            v2_name = re.sub(pattern, '', v2_decode)            
            v2_strip = v2_name.strip()
            data_dict[i] = v2_strip

            
        
    with open('version.json', 'r ') as f:
        json.dump(data_dict, f, indent=4)

        

if __name__ == '__main__':
    getData()

So far i'm getting the JSON below but I would like to leave it as the file I left above - with a key (software | version):

{
    "node": "10.19.0",
    "python3": "3.8.10",
    "ansible": "2.9.6",
    "perl": "5.30.0"
}   

Thanks in advance :)

CodePudding user response:

Here's how you can do it. First you need to make data_dict into a list, since you have the same structure in JSON. Then, on each iteration you can do: data_list.append(dict(software=i, version=version)). One other change I added was to use the w flag when opening a file instead of r , so we can open it in write-only mode.

I included only the relevant parts of the code where I added changes:

data_list = []

def getData():
    for i in data:
        if i == "perl":
            ...
            version = v1_strip

        else:
            ...
            version = v2_strip

        data_list.append(dict(software=i, version=version))

    with open('version.json', 'w') as f:
        json.dump(data_list, f, indent=4)
  • Related