Reputation: 953
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 dump the id and text in json so that I get the desired output.
Upvotes: 3
Views: 8011
Reputation: 107347
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 loop over you lines and split it, then create your expected dictionary.you can use dict.setdefault
method for this task.
Then use json.dump
to write your data to file!
Upvotes: 4