Search code examples
arraysjsonpython-3.xformattxt

How to convert list from txt file to Json


I have a very long list of phonenumbers in a .txt file that i need to convert into a json to store and from there into an array.

the list is formatted like this in the txt file.

phonenumber: value1
phonenumber: value2
phonenumber: value3

and so on.

my aim is to get them formatted into json properly so i can use them in an array.

I have tried the following code to do so however i was unable to get it into the correct format

f = open("phone+.txt", "r")
content = f.read()
splitcontent = content.splitlines()

d = []
for v in splitcontent:
    l = v.split(': ')
    d.append(list(s.split(': ',1) for s in l))


with open("phone_list.json", "w") as file:
    file.write((json.dumps(d, indent=4, sort_keys= False)))

The result i got from this was as follows

[
    [
        [
            "phonenumber"
        ],
        [
            "value1"
        ]
    ],
    [
        [
            "phonenumber"
        ],
        [
            "value2"
        ]
    ],
    [
        [
            "phonenumber"
        ],
        [
            "value2"
        ]
    ]
]

Solution

  • Line d.append(list(s.split(': ',1) for s in l)) doesn't make sense. No need to split again.

    You just need:

    d = []
    for v in splitcontent:
        l = v.split(': ') # here we're already spliting each line by colon i.e. phonenumber: value1
        d.append(l)
    

    and it'll give you a nice list:

    [['phonenumber', 'value1'], ['phonenumber', 'value2'], ['phonenumber', 'value3']]