Ravi Teja Kothuru
Ravi Teja Kothuru

Reputation: 19

Convert output to JSON in Python

I have executed few Linux commands using Python code. Please refer the code below with the output.

import os

uptime_from_top_command = "top -c -b -n1 | head -1 | cut -d ' ' -f 4-6 | sed -e 's/,//'"
uptime = os.system(uptime_from_top_command)

load_average_from_top_command = "top -c -b -n1 | head -1 | cut -d ',' -f 4-6 | sed -e 's/^[ \t]*//'"
load_average = os.system(load_average_from_top_command)

I got the below output.

up 100 days
load average: 0.06, 0.04, 0.00

I need to convert this output into the below JSON format and store it inside a JSON file.

{
    "uptime": "100 days",
    "load average": {
        "1_min": "0.06",
        "5_mins": "0.04",
        "15_mins": "0.00"
    }
}

Note - If the uptime of a server is less than 1 day, then it'll be displayed as up 12:45(for example). In that case, it should be converted to a JSON file in below format.

{
    "uptime": "12:45",
    "load average": {
        "1_min": "0.06",
        "5_mins": "0.04",
        "15_mins": "0.00"
    }
}

I mean, it should accept both the formats.

Please could someone help me how to achieve this?

Upvotes: 0

Views: 1010

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195438

You can try re module to parse the string output. For example:

import re

s = """\
up 100 days
load average: 0.06, 0.04, 0.00"""

out = {
    "uptime": re.search(r"up ([^\s]+(?: days?)?)", s).group(1),
    "load average": dict(
        zip(
            ("1_min", "5_mins", "15_mins"),
            re.search(r"load average: ([^\s]+) ([^\s]+) ([^\s]+)", s).groups(),
        )
    ),
}

print(out)

Prints:

{
    "uptime": "100 days",
    "load average": {"1_min": "0.06,", "5_mins": "0.04,", "15_mins": "0.00"},
}

EDIT: To save data in Json file:

import re
import json

s = """\
up 100 days
load average: 0.06, 0.04, 0.00"""

out = {
    "uptime": re.search(r"up ([^\s]+(?: days?)?)", s).group(1),
    "load average": dict(
        zip(
            ("1_min", "5_mins", "15_mins"),
            re.search(r"load average: ([^\s]+) ([^\s]+) ([^\s]+)", s).groups(),
        )
    ),
}

with open("data.json", "w") as f_out:
    json.dump(out, f_out, indent=4)

Saves the data to data.json:

{
    "uptime": "100 days",
    "load average": {
        "1_min": "0.06,",
        "5_mins": "0.04,",
        "15_mins": "0.00"
    }
}

Upvotes: 1

Related Questions