Issue
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"
}
]
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"}]
Answered By - SorousH Bakhtiary
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.