Reputation: 13
I am new bee to python I need your help/suggestion, I am trying to convert the content of text file to json using python
filename is json_content.txt. Below is the content of text file
hostname : WGNAIOP
fsystem : /dev/sdb
actual_size : 2.5T
used_disk : 609G
avail_disk : 1.7T
percentage : 26%
mount_disk : /data
hostname : WNQAIOP
fsystem : /dev/sdb
actual_size : 2.5T
used_disk : 526G
avail_disk : 1.8T
percentage : 23%
mount_disk : /data
I have tried in multiple ways but i am unable to get the result in json format. Please help me to know how i can convert the above text data into json
Thanking in Advance!!!
Upvotes: 0
Views: 1343
Reputation: 1115
json_data = {}
with open("json_content.txt","r") as fp:
for line in fp.readlines():
if line != "\n":
split_data = line.split(':',)
print(split_data)
json_data[split_data[0]] = split_data[1].split('\n')[0]
print(json_data)
Output:
{'hostname': 'WGNAIOP', 'fsystem': '/dev/sdb', 'actual_size': '2.5T', 'used_disk': '609G', 'avail_disk': '1.7T', 'percentage': '26%', 'mount_disk': '/data'}
Upvotes: 1
Reputation: 104
Here's a similar solution as the other answer.
import re
import json
tfile='/home/json_content.txt'
input = None
with open(tfile) as infile:
input = infile.readline()
# remove leading and trailing double quotes if needed
# input = input.strip('"')
pattern = re.compile("\S* : \S*")
match = pattern.findall(input)
data = {}
for kvp in match:
values = kvp.split(' : ')
data[values[0]] = values[1]
data_json = json.dumps(data)
print(data_json)
Upvotes: 0
Reputation: 2518
Unless you have any whitespaces in either the key or the value, you can use this regular expression to transorm your content to a dictonary:
line = 'hostname : WGNAIOP fsystem : /dev/sdb actual_size : 2.5T used_disk : 609G avail_disk : 1.7T'
d_items = re.findall(r"(\S+\s:\s\S+)", line)
d = dict()
for d_item in d_items:
k, v = d_item.split(" : ")
d[k] = v
For the lines provided the snippet works:
print(d)
# {'hostname': 'WGNAIOP', 'fsystem': '/dev/sdb', 'actual_size': '2.5T', 'used_disk': '609G', 'avail_disk': '1.7T'}
Upvotes: 0