Home > database >  Create json from shell script output
Create json from shell script output

Time:04-25

I have a shell script version.sh in which i have code like.

#!/bin/sh
data = `lsb_release -a`
echo $data

it returned me the output like:

Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:    20.04
Codename:   focal

so what I exactly want is want a JSON file to be created .and data should be there like

{'Release' : 20.04 , 'Codename' : focal}

I want to print data in JSON form .can anyone please help me related this ?? I am stuck here.any suggestion any help would be matter.

CodePudding user response:

You can use python ttp module to get this data. See the following example:

from ttp import ttp
import json

data_to_parse = """
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:    20.04
Codename:   focal
"""

ttp_template = """
Release:    {{release}}
Codename:   {{codename}}

"""

parser = ttp(data=data_to_parse, template=ttp_template)
parser.parse()

# print result in JSON format
results = parser.result(format='json')[0]
#print(results)

#converting str to json. 
result = json.loads(results)

print(result)

See the output:

enter image description here

EDITED as requested (without using any package):

data_to_parse = """
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:    20.04
Codename:   focal
"""

lines = data_to_parse.splitlines()

result = {}

for line in lines:
    if 'Release:' in line:
        line2 = line.split(':')
        result['Release'] = (line2[1].strip())

    elif 'Codename:' in line:
        line2 = line.split(':')
        result['Codename'] = (line2[1].strip())

print(result)

See the result:

enter image description here

EDITED 2. time:

New Data:

data_to_parse = """
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:    20.04
Codename:   focal

Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:    22.04
Codename:   local

Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:    21.04
Codename:   cocal

"""

The code:

lines = data_to_parse.splitlines()

result_list = []
result2 = {}
result_list3 = []

for line in lines:
    
    if 'Release:' in line:
        line2 = line.split(':')
        result_list.append({'Release': line2[1].strip()})
    
    elif 'Codename:' in line:
        line2 = line.split(':')
        result_list.append({'Codename': line2[1].strip()})
        result2 = {**result_list[0], **result_list[1]}
        result_list3.append(result2)
        result_list = []

print(result_list3)

The output:

enter image description here

  • Related