0

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]
3
  • List comp which generate list of dicts: [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 use json.dumps() with indent argument: 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)). Commented Oct 12, 2020 at 13:14
  • @OlvinRoght:Facing this error: ValueError: dictionary update sequence element #11 has length 1; 2 is required Commented Oct 12, 2020 at 13:19
  • It means that format of your file is different form example you provided in question. This error means that one of line doesn't contain ':' so str.split() returns list with single element. Commented Oct 12, 2020 at 13:23

1 Answer 1

1
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"))
Sign up to request clarification or add additional context in comments.

2 Comments

this worked fine with few modifications. Thanks. In dictionary, 1 key has multi line value. While fetching that key, only single line value is being fetched. Is there any way by which I can fetch all the lines ?
if there is only one such key, then you can use couple of if conditions to make sure you are fetching value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.