Reputation: 75
I am trying to use Streaming Api of twitter and tweepy to get some tweets filtered by some keywords(already done) and their coordinates which I can later plot on google map. However i am getting an error when I am executing the following code to store only those tweets where coordinates are not null.
Code:
def on_data(self, data):
json_object = json.loads(data)
if (json_object["user"]["coordinates"]!="null"):
f.write(data)
After some time I get an error that says
Key error:user
Can anybody tell me the reason why this error happened and what steps can be taken to resolve or understand this error better.
Upvotes: 2
Views: 1053
Reputation: 5860
You are getting this error because its not necessary all the tweets will have the user
field.
def on_data(self, data):
json_object = json.loads(data)
# next statement will short circuit if 'user' field is not found.
if "user" in json_object and "coordinates" in json_object["user"] and json_object["user"]["coordinates"]!="null":
f.write(data)
Or if you want to do this gracefully -
def on_data(self, data):
try:
if json_object["user"]["coordinates"]!="null":
f.write(data)
except:
pass
Upvotes: 3