Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json KeyError with json.loads

Tags:

python

json

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?

like image 716
user322775 Avatar asked Apr 21 '10 23:04

user322775


2 Answers

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}}}

like image 131
ChronoPositron Avatar answered Oct 04 '22 18:10

ChronoPositron


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).

like image 38
törzsmókus Avatar answered Oct 04 '22 17:10

törzsmókus