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

问题描述 投票:0回答:2

首先,在编写python时,我总是noob所以我到目前为止所做的很多事情都已经学习了,因为我这样说过:

我这里有一些代码

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的归还方式有关。问题是当它被抛出时会杀死脚本,就是这样。谢谢您的帮助。

python json api python-requests
2个回答
0
投票

我认为这个错误是因为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

1
投票

问题是你的响应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'
© www.soinside.com 2019 - 2024. All rights reserved.