如何正确处理json响应中的错误

2024-10-01 09:15:42 发布

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

首先,在编写python时,我完全是个呆子,所以到目前为止,我所做的很多工作都是在学习的过程中完成的,我说:

我这里有一些代码

if buycott_token != '':
    print("Looking up in Buycott")
    url = "https://www.buycott.com/api/v4/products/lookup"
    headers = {
    'Content-Type': 'application/json'
    }
    data={'barcode':upc,
          'access_token':buycott_token
         }
    try:
        r = requests.get(url=url, json=data, headers=headers)
        j = r.json()
        if r.status_code == 200:
        print("Buycott found it so now we're going to gather some info here and then add it to the system")
        name = j['products'][0]['product_name']
        description = j['products'][0]['product_description']
        #We now have what we need to add it to grocy so lets do that
        #Sometimes buycott returns a success but it never actually does anything so lets just make sure that we have something
        if name != '':
            add_to_system(upc, name, description)
    except requests.exceptions.Timeout:
        print("The connection timed out")
    except requests.exceptions.TooManyRedirects:
        print ("Too many redirects")
    except requests.exceptions.RequestException as e:
        print e  

98%的时间,这只是工作没有问题。然后我用条形码扫描器扫描一些东西

Traceback (most recent call last):
  File "./barcode_reader.py", line 231, in <module>
    increase_inventory(upc)
  File "./barcode_reader.py", line 34, in increase_inventory
    product_id_lookup(upc)
  File "./barcode_reader.py", line 79, in product_id_lookup
    upc_lookup(upc)
  File "./barcode_reader.py", line 128, in upc_lookup
    name = aj['products'][0]['product_name']
KeyError: 'products'

我确信这与json是如何返回的有关。问题是当这个被抛出时,它会杀死脚本。谢谢你的帮助


Tags: tonameinjsonitproductlookuprequests
2条回答

问题是您的响应JSON中没有'products'键。如果'products'键不存在,解决方法可以提供一个默认值:

default_value = [{'product_name': '', 'product_description': ''}]
j.get('products', default_value)[0]['product_name']

或者您可以简单地检查您的响应是否具有产品密钥:

if 'products' not in j:
    return 'Product not found'

我认为这个错误是因为API没有给出正确的json响应。所以我认为您可以从您的侧面检查密钥是否在API响应中

if 'products' in j:
   name = j['products'][0]['product_name']
   description = j['products'][0]['product_description']
else:
   #Whatever you want when 'product' is not in API response

相关问题 更多 >