如何正确错误检查Python中的JSON值?

时间:2013-08-07 07:41:06

标签: python json error-handling

好的,我有这个代码,我从instagram的api中得到一些json ....

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

但有时候

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

可能没有任何数据。 然后我回来了。

      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

错误检查或防御性编码不是我的专长...... 那么如果json值= None

,如何使代码通过

我试过这样做,但无济于事......

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

1 个答案:

答案 0 :(得分:1)

如果您想尽可能多地填写MSG字典,则需要单独添加每个值:

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'] = ""

或者,为避免违反DRY原则:

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] = ""