Writing tab delimited file as a json object in python
I have a tab delimited file of the form:
123 91860 Sun Mar 16 08:06:25 +0000 2014 feeling terrible.
789 12139 Sun Mar 16 09:01:07 +0000 2014 children are the blessing of god.
Now I want to write this file as a json object like this:
{"data": [{"text": "feeling terrible.","id": 123},{"text": "children are the blessing of god","id": 678}]}
I want to write the code for this in python:
import json
f=open("tree_0","r")
for line in f:
lines=line.split('\n')
data=lines[0].split("\t")
id=str(data[0])
text=str(data[3])
Please tell me how to reset the id and text in json to get the desired result.
+3
source to share
1 answer
You can do the following:
import json
data={}
with open('data.txt', 'w') as outfile,open("tree_0","r") as f:
for line in f:
sp=line.split()
data.setdefault("data",[]).append({"text": sp[-1],"id": sp[0]})
json.dump(data, outfile)
All you need is to loop over your lines and break it down and then create the expected dictionary. You can use the dict.setdefault
method for this task.
Then use json.dump
to write your data to a file!
+3
source to share