如何在Python中正确检查JSON值?

2024-03-28 15:49:56 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我有一段代码,我从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

Tags: 代码textapijsondatamsginstagramuser
1条回答
网友
1楼 · 发布于 2024-03-28 15:49:56

如果要尽可能多地填充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'] = ""

或者,为了避免违反干燥原则:

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

相关问题 更多 >