sirvon
sirvon

Reputation: 2625

How to correctly error check JSON value in Python?

OK, I have this code where i'm getting some json back from instagram's api....

      instaINFO = requests.get("https://api.instagram.com/v1/media/%s?access_token=xyz" % instaMeID).json()
      print instaINFO
      #pdb.set_trace()
      MSG = {'fromEMAIL': uEmail, 'toCHANNELID': channelID, 'timeSENT': uTi    me, 'profilePIC': instaINFO['data']['user']['profile_picture'],'userNAME': instaINFO[    'data']['user']['username'], 'msgBODY': instaINFO['data']['caption']['text']}

but sometimes

       instaINFO['data']['caption']['text'] 

might not have any data. and I get this back.

      MSG = {'fromEMAIL': uEmail, 'toCHANNELID': channelID, 'timeSENT': uTime,
      'profilePIC': instaINFO['data']['user']['profile_picture'],'userNAME':
      instaINFO['data']['user']['username'], 'msgBODY': instaINFO['data']['caption']
      ['text']}
      TypeError: 'NoneType' object is not subscriptable

error checking or defensive coding is not my speciality... So how do I make the code pass if a json value = None

I've tried to do this but to no avail...

      if instaINFO['data']['caption']['text'] == None:
       pass

Upvotes: 0

Views: 124

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336148

If you want to fill the MSG dictionary as much as possible, you need to add each value separately:

MSG = {'fromEMAIL': uEmail, 'toCHANNELID': channelID, 'timeSENT': uTime}
try:
    MSG['profilePIC'] = instaINFO['data']['user']['profile_picture']
except TypeError:
    MSG['profilePIC'] = ""
try:
    MSG['userNAME'] = instaINFO['data']['user']['username']
except TypeError:
    MSG['userNAME'] = ""
try:
    MSG['msgBODY'] = instaINFO['data']['caption']['text']
except TypeError:
    MSG['msgBODY'] = ""

or, to avoid violating the DRY principle:

MSG = {'fromEMAIL': uEmail, 'toCHANNELID': channelID, 'timeSENT': uTime}
for mkey, subdict, ikey in (('profilePIC', 'user', 'profile_picture'), 
                            ('userNAME', 'user', 'username'),
                            ('msgBODY', 'cpation', 'text')):
    try:
        MSG[msgkey] = instaINFO['data'][subdict][instakey]
    except TypeError:
        MSG[msgkey] = ""

Upvotes: 1

Related Questions