python – json KeyError with json.loads

python – json KeyError with json.loads

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:

Ive 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:

{ufavorited: False, ucontributors: None, utruncated: False, utext: —- snip —- }

Sample Chunk #2:

{udelete: {ustatus: {uuser_id: 55389449, uid: 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).

python – json KeyError with json.loads

Is it because there is no text key in the line or because delete is not in the dictionary?

Its because there is no text key. If you print temp or check whether the key text is in the resulting Python dictionary, youll notice that there is no key named text. In fact, temp only has one key: delete. The dictionary that is referenced by delete contains a single key status that contains another dictionary with two keys: user_id and id.

In other words, your structure is this:

{
    delete : {
        status : {
            id : 12600579001,
            user_id : 55389449
        }
    }
}

As you can see, there is no text key anywhere.

Furthermore, you can check it yourself:

>>> text in temp
False
>>> delete in temp
True

Leave a Reply

Your email address will not be published. Required fields are marked *