I have formatted txt file looks like this:
Hostinfo Start
DATE 190819 1522
HOST midas
DOMAIN test.de
HW_PLATFORM x86_64
SERVER_TYPE virtual
CPU_INFO
CPU_TYPE Intel(R) Xeon(R) CPU E7-8867 v4 @ 2.40GHz
CPU_COUNT 2
CORE_COUNT 2
THREAD_COUNT 8
MEMORY 32951312 kB
OS Start
OS Linux
OS_VERSION 4.9.0-6-amd64
OS_UPTIME 536 days 21:08
OS End
RELEASE Debian GNU/Linux 9 (stretch)
RELEASE_VERSION 9
RELEASE_PATCHLEVEL
Hostinfo End
Using the count of leading spaces need to convert it to json format looking similar to this:
"Hostinfo": [
{
"DATE": "190819 1522"
"HOST": "midas"
"DOMAIN": "test.de"
"HW_PLATFORM": "x86_64"
"SERVER_TYPE": "virtual"
"CPU_INFO": {
"CPU_TYPE": "Intel(R) Xeon(R) CPU E7-8867 v4 @ 2.40GHz"
"CPU_COUNT": "2"
"CORE_COUNT": "2"
}
"THREAD_COUNT": "8"
"MEMORY": "32951312 kB"
"OS": [
{
"OS": "Linux"
"OS_VERSION": "4.9.0-6-amd64"
"OS_UPTIME": "536 days 21:08"
}
]
"RELEASE": "Debian GNU/Linux 9 (stretch)"
"RELEASE_VERSION": "9"
"RELEASE_PATCHLEVEL" : ""
}
]
I have some undertakings of this script but can't workaround how to set lines between curly brackets as object of upper dictionary (level):
#!/usr/bin/python
import json
import itertools
import string
import re
filename = 'commands.txt'
commands = {}
with open(filename) as fh:
previous_line = 0
mark_line = ""
for line in fh:
current_line = ((len(line) - len(line.lstrip()))/2)
diff = current_line - previous_line
if re.search(' Start$', line.strip()):
line = line.strip().replace(' Start', ':{')
print(line)
mark_line = "start_line"
elif re.search(' Ende$', line.strip()):
line = line.strip().replace(' Ende', '')
print("}")
mark_line = "end_line"
elif diff == 0:
print(line.strip())S
elif diff > 0:
if mark_line == "start_line" or mark_line == "end_line":
mark_line = "0"
else:
print("{")
print(line.strip())
elif diff < 0:
if mark_line == "start_line" or mark_line == "end_line":
mark_line = "0"
else:
print("}")
print(line.strip())
previous_line = ((len(line) - len(line.lstrip()))/2)
#line = (str((len(line) - len(line.lstrip()))/2) + ";" + line.strip())
try:
command, description = line.strip().split(' ', 1)
commands[command] = description.strip()
except Exception:
command = line.strip()
description = ""
commands[command] = description.strip()
print(json.dumps(commands, indent=2, sort_keys=True))
May be you can get me some idea how to workaround this or take some advice? May it would be some module that simplifies this script?
UPD: add some json markup to my mess script. Can you please get advice if I moving at wrong/right way?