JSON seems to be hiccuping on the following statements:
{"delete":{"status":{"id":12600579001,"user_id":55389449}}}
code snippet:
temp = json.loads(line)
text = temp['text']
I get the following error output when the above code snippet encounters lines similar to the above JSON 'dictionary':
text = temp['text']
KeyError: 'text'
Is it because there is no "text" key in the line or because "delete" is not in the dictionary?
It looks like this happens because 'text' is not in there. Maybe you could use something like
'text' in temp
to check that 'text' exists before trying to use it.
Edit:
I've taken the example given in the comment and added a if/elif/else block to it.
#! /usr/bin/python
import sys
import json
f = open(sys.argv[1])
for line in f:
j = json.loads(line)
try:
if 'text' in j:
print 'TEXT: ', j['text']
elif 'delete' in j:
print 'DELETE: ', j['delete']
else:
print 'Everything: ', j
except:
print "EXCEPTION: ", j
Sample Chunk #1:
{u'favorited': False, u'contributors': None, u'truncated': False, u'text': ---- snip ---- }
Sample Chunk #2:
{u'delete': {u'status': {u'user_id': 55389449, u'id': 12600579001L}}}
use dict.get(key[, default]) if there is a valid case when the key is missing:
temp.get('text')
instead of temp['text']
won’t throw an exception but return the null value None
if the key is not found.
EAFP (Easier to Ask for Forgiveness than Permission) is more Pythonic than LBYL (Look Before You Leap).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With