使用 Python 访问 JSON 元素

Accessing JSON Elements W/ Python

我想访问 'vin'、'make'、'year' 等的个人数据并导出到 csv。我试过通过

访问它
response = requests.request("POST", url, headers=headers, data=payload, timeout=15)

response_json = response.json()
#print(response_json)

for item in response_json['data']['hits']['hits']:
    
      active_year = item['year']
      active_make = item['make']
      active_model = item['model']
      active_trim = item['trim']
      active_vin = item['vin']
      active_mileage = item['mileage']
      active_basePrice = item['price']
                    
    
      print(str(active_year) + " " + active_vin + " " + active_make)

我得到一个 KeyError:'year'

这是我正在使用的 JSON 树的一部分

`{
    "data": {
        "took": 31,
        "timed_out": false,
        "hits": {
            "total": 15786,
            "hits": [
                {
                    "_source": {
                        "vin": "JTHBW1GG0H2142332",
                        "stockNumber": "",
                        "bodyType": "Sedan",
                        "interiorPhotoUrl": "https://cdn.spincar.com/swipetospin-viewers/vroomadesaatlanta/jthbw1gg0h2142332/20201203212657.Z81AZWJL/closeups/cu-10.jpg",
                        "diesel": 0,
                        "leadFlagPhotoUrl": "https://cdn.spincar.com/swipetospin-viewers/vroomadesaatlanta/jthbw1gg0h2142332/20201203212657.Z81AZWJL/closeups/cu-0.jpg",
                        "listingPrice": 26980,
                        "color": "Black",
                        "year": 2017,`

我只是对语法有点困惑,因为我以同样的方式访问二维数组中的数据。

您跳过了 json 的“_source”部分。这应该可以解决它。

response = requests.request("POST", url, headers=headers, data=payload, timeout=15)

response_json = response.json()
#print(response_json)

for item in response_json['data']['hits']['hits']:
      source = item['_source'] # THIS WAS MISSING
    
      active_year = source['year']
      active_make = source['make']
      active_model = source['model']
      active_trim = source['trim']
      active_vin = source['vin']
      active_mileage = source['mileage']
      active_basePrice = source['price']
                    
    
      print(str(active_year) + " " + active_vin + " " + active_make)