json - 为什么我无法从字典中检测到 None 值
问题描述
我已经多次看到这个问题发生在很多人身上(这里)。我仍在努力验证我的字典从 JSON 中捕获的内容是否为“无”,但我仍然收到以下错误。这段代码应该调用一个 CURL,在“状态”键中查找“关闭”值,直到找到它(或 10 次)。当通过二维码完成支付时,状态会从打开状态变为关闭状态。
status = (my_dict['elements'][0]['status'])
TypeError: 'NoneType' object is not subscriptable
关于我做错了什么以及如何解决它的任何线索?此外,如果我单独运行调用 JSON 的脚本部分,它每次都能顺利执行。代码中是否有任何可能影响 CURL 执行的内容?顺便说一句,我一周前开始编程,所以如果我混淆概念或说一些缺乏常识的话,请原谅。
我试图用“is not”而不是“!=”以及“None”而不是“”来验证 IF。
def show_qr():
reference_json = reference.replace(' ','%20') #replaces "space" with %20 for CURL assembly
url = "https://api.mercadopago.com/merchant_orders?external_reference=" + reference_json #CURL URL concatenate
headers = CaseInsensitiveDict()
headers["Authorization"] = "Bearer MY_TOKEN"
pygame.init()
ventana = pygame.display.set_mode(window_resolution,pygame.FULLSCREEN) #screen settings
producto = pygame.image.load("qrcode001.png") #Qr image load
producto = pygame.transform.scale(producto, [640,480]) #Qr size
trials = 0 #sets while loop variable start value
status = "undefined" #defines "status" variable
while status != "closed" and trials<10: #to repeat the loop until "status" value = "closed"
ventana.blit(producto, (448,192)) #QR code position setting
pygame.display.update() #
response = requests.request("GET", url, headers=headers) #makes CURL GET
lag = 0.5 #creates an incremental 0.5 seconds everytime return value is None
sleep(lag) #
json_data = (response.text) #Captures JSON response as text
my_dict = json.loads(json_data) #creates a dictionary with JSON data
if json_data != "": #Checks if json_data is None
status = (my_dict['elements'][0]['status']) #If json_data is not none, asigns 'status' key to "status" variable
else:
lag = lag + 0.5 #increments lag
trials = trials + 1 #increments loop variable
sleep (5) #time to avoid being banned from server.
print (trials)
解决方案
从您最初遇到的错误来看,尚不清楚问题是什么。问题是,基本上该语句的任何部分都可能导致TypeError
被引发,因为评估的部分是无。例如,如果是 None,或者如果是 None,my_dict['elements'][0]['status']
这可能会失败。my_dict
my_dict['elements']
我会尝试插入断点以更好地帮助调试原因。另一个可能有帮助的解决方案是将语句的每个部分包装在一个try-catch
块中,如下所示:
my_dict = None
try:
elements = my_dict['elements']
except TypeError as e:
print('It possible that my_dict maybe None.')
print('Error:', e)
else:
try:
ele = elements[0]
except TypeError as e:
print('It possible that elements maybe None.')
print('Error:', e)
else:
try:
status = ele['status']
except TypeError as e:
print('It possible that first element maybe None.')
print('Error:', e)
else:
print('Got the status successfully:', status)
推荐阅读
- python - 十进制转二进制 Python R2L 格式
- javascript - 检测到变化时角闪烁
- rpm - 在 CentOS 8 的本地存储库中安装 httpd
- mysql - 错误 1045 (28000):在终端上使用以下命令拒绝用户 'root'@'localhost'(使用密码:NO)的访问:sudo mysql、和、、mysql
- c++ - 展平到一维的优势
- graphql - Graphql 类型解析器(按 id)
- javascript - 函数正常执行但 addeventlistener 不会执行函数
- database - Spark 避免每次执行整个查询
- python - 与在 vscode 中使用 Go to Definition 和 Peek Definition 命令相关
- amazon-web-services - Terraform 错误:运行 terraform 计划时条件类型不正确