【问题标题】:How to handle a Python (JSON) key error when I know the key exists?当我知道密钥存在时如何处理 Python (JSON) 密钥错误?
【发布时间】:2020-12-11 06:55:13
【问题描述】:

我正在尝试运行以下代码,我知道密钥“vin”存在,但不断收到密钥错误。如何在代码中处理这个问题?

#page_url = 'https://www.cargurus.com/Cars/inventorylisting/viewDetailsFilterViewInventoryListing.action?zip=32805&inventorySearchWidgetType=PRICE&maxPrice=42500&maxMileage=50000&showNegotiable=false&sortDir=DESC&sourceContext=carGurusHomePageModel&distance=100&minPrice=0&sortType=PRICE&minMileage=0&sellerTypes=PRIVATE'

data = []
offset = 0
while True:
    print('Offset {}...'.format(offset))
    json_data = requests.get(page_url.format(offset)).json()
    
    for listing in json_data:
        jdata = requests.get(page_url.format(offset)).json()
        listing_title = listing['listingTitle']
        vehicle_id = listing['id']
        price = listing['price']
        year = listing['carYear']
        make_name = listing['makeName']
        model_name = listing['modelName']
        mileage = listing['mileage']
        vin = listing['vin']
        
        # ... other data

        #print((jdata, listing_title, vehicle_id, price, year, make_name, model_name, mileage, vin))

【问题讨论】:

  • 你得到一个KeyError,然后密钥不存在。
  • 可以分享json_data的内容吗?

标签: python json key keyerror


【解决方案1】:

将代码的最后一行更改为如下所示:

try:
    vin = listing['vin']
except KeyError:
    print(f"'vin' not found in {listing}")

这将告诉您 (1) 密钥实际上并不存在于您的所有数据项中,仅存在于其中的 一些 项中; (2) 如何在代码中处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多