Looking Forward
Looking Forward

Reputation: 3585

Convert file string data to json python

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]

Upvotes: 0

Views: 122

Answers (1)

LMKR
LMKR

Reputation: 647

def convert(file_name):
    objects = []
    with open(file_name) as f:
        d = {}
        for line in f:
            if line.startswith("Age"):
                key, value = line.split(":")
                d[key.strip()] = value.strip()
                objects.append(d)
                d = {}
            else:
                try:
                    key, value = line.split(":")
                    d[key.strip()] = value.strip()
                except ValueError as v:
                    pass

    return objects
print(convert("infile.txt"))

Upvotes: 1

Related Questions