【问题标题】:How to correctly error check JSON value in Python?如何在 Python 中正确错误检查 JSON 值?
【发布时间】:2013-08-07 07:41:06
【问题描述】:

好的,我有这段代码,我从 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值=无,我如何让代码通过

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

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

【问题讨论】:

  • data 键是空的还是caption 键?
  • 如果缺少密钥,您希望发生什么?另外(顺便说一句)检查None 单例不应该使用==,而是使用is
  • 如果缺少密钥,我希望用“”填充的值和脚本继续运行。如果某人的 Instagram 标题未填写,脚本将停止运行。

标签: python json error-handling


【解决方案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] = ""

【讨论】:

猜你喜欢
  • 2020-09-24
  • 1970-01-01
  • 2020-03-22
  • 1970-01-01
  • 1970-01-01
  • 2013-06-12
  • 1970-01-01
  • 2013-03-06
  • 2018-02-27
相关资源
最近更新 更多