I want to access the individual data for ‘vin’, ‘make’, ‘year’, etc and export to a csv. I have tried accessing it by
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)
I get a KeyError: ‘year’
This is part of the JSON tree I am working with
`{ "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,`
I am just a bit confused on the syntax as I have access data from a 2D array in this same manner.
Advertisement
Answer
You skipped the ‘_source’ section of json. This should fix it.
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)