I've file where data is in below string format.
Name : XYZ
Address : London
Occupation : Teacher
Age : 34
Name : ABC
Address : New York
Occupation : Business
Age : 39
I want to convert data to json as show in below format:
{
Name : XYZ
Address : London
Occupation : Teacher
Age : 34
},
{
Name : ABC
Address : New York
Occupation : Business
Age : 39
}
I've tried below so far:
def convert() :
f = open("file.txt", "r")
content = f.read()
splitcontent = content.splitlines()
data = json.dumps(splitcontent, default=lambda o: o.__dict__)
print(data)
O/P: [Name : XYZ, Address : London, Occupation : Teacher, Age : 34, Name : ABC, Address : New York, Occupation : Business, Age : 39]
[dict((i.strip() for i in l.split(':')) for l in s.splitlines()) for s in file_data.split('\n\n')]. To print it nice usejson.dumps()withindentargument:print(json.dumps([dict((i.strip() for i in l.split(':')) for l in s.splitlines()) for s in file_data.split('\n\n')], indent=4)).':'sostr.split()returns list with single element.