gpt4 book ai didi

python - 如何在Python中正确错误检查JSON值?

转载 作者:行者123 更新时间:2023-12-03 08:33:06 25 4
gpt4 key购买 nike

OK,我有这段代码,我从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

最佳答案

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

关于python - 如何在Python中正确错误检查JSON值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18097439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com