首页 > 解决方案 > 为什么我无法从字典中检测到 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)

标签: jsonpython-3.xnonetype

解决方案


从您最初遇到的错误来看,尚不清楚问题是什么。问题是,基本上该语句的任何部分都可能导致TypeError被引发,因为评估的部分是无。例如,如果是 None,或者如果是 None,my_dict['elements'][0]['status']这可能会失败。my_dictmy_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)

推荐阅读