Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting a text file to JSON using Python

I have a text file which contains:

b770d5b4bb6b594daf985845aae9aa5f:b0cb46d2d31cf044bc73db71e9865f6f
a6cde1a737b44799ad78f1c1df3bcc2d:77aa72de248cf3649d052a49995c0c84
555040e976be48cebea579309f4e6339:2b0003ca52ffc309ef76872c5ab3729c

Which code in Python could be used for converting the text file to a JSON file looks like this:

[
{
"kid": "b770d5b4bb6b594daf985845aae9aa5f",
"hex_key": "b0cb46d2d31cf044bc73db71e9865f6f"
},
{
"kid": "a6cde1a737b44799ad78f1c1df3bcc2d",
"hex_key": "77aa72de248cf3649d052a49995c0c84"
},
{
"kid": "555040e976be48cebea579309f4e6339",
"hex_key": "2b0003ca52ffc309ef76872c5ab3729c"
}
]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can read each line, split it with ':' and build a dictionary with these two values. Then append the dictionary to a list. Finally you can use json.dumps to convert your Python object(list) to a string which is in JSON format.

import json

res = []
with open('<Path to file.txt>') as f:
    for line in f:
        kid, hex_key = line.strip().split(':')
        res.append({'kid': kid, 'hex_key': hex_key})

print(json.dumps(res))

output:

[{"kid": "b770d5b4bb6b594daf985845aae9aa5f", "hex_key": "b0cb46d2d31cf044bc73db71e9865f6f"}, {"kid": "a6cde1a737b44799ad78f1c1df3bcc2d", "hex_key": "77aa72de248cf3649d052a49995c0c84"}, {"kid": "555040e976be48cebea579309f4e6339", "hex_key": "2b0003ca52ffc309ef76872c5ab3729c"}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading