I want to access the individual data for ‘vin’, ‘make’, ‘year’, etc and export to a csv. I have tried accessing it by
JavaScript
x
18
18
1
response = requests.request("POST", url, headers=headers, data=payload, timeout=15)
2
3
response_json = response.json()
4
#print(response_json)
5
6
for item in response_json['data']['hits']['hits']:
7
8
active_year = item['year']
9
active_make = item['make']
10
active_model = item['model']
11
active_trim = item['trim']
12
active_vin = item['vin']
13
active_mileage = item['mileage']
14
active_basePrice = item['price']
15
16
17
print(str(active_year) + " " + active_vin + " " + active_make)
18
I get a KeyError: ‘year’
This is part of the JSON tree I am working with
JavaScript
1
19
19
1
`{
2
"data": {
3
"took": 31,
4
"timed_out": false,
5
"hits": {
6
"total": 15786,
7
"hits": [
8
{
9
"_source": {
10
"vin": "JTHBW1GG0H2142332",
11
"stockNumber": "",
12
"bodyType": "Sedan",
13
"interiorPhotoUrl": "https://cdn.spincar.com/swipetospin-viewers/vroomadesaatlanta/jthbw1gg0h2142332/20201203212657.Z81AZWJL/closeups/cu-10.jpg",
14
"diesel": 0,
15
"leadFlagPhotoUrl": "https://cdn.spincar.com/swipetospin-viewers/vroomadesaatlanta/jthbw1gg0h2142332/20201203212657.Z81AZWJL/closeups/cu-0.jpg",
16
"listingPrice": 26980,
17
"color": "Black",
18
"year": 2017,`
19
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.
JavaScript
1
19
19
1
response = requests.request("POST", url, headers=headers, data=payload, timeout=15)
2
3
response_json = response.json()
4
#print(response_json)
5
6
for item in response_json['data']['hits']['hits']:
7
source = item['_source'] # THIS WAS MISSING
8
9
active_year = source['year']
10
active_make = source['make']
11
active_model = source['model']
12
active_trim = source['trim']
13
active_vin = source['vin']
14
active_mileage = source['mileage']
15
active_basePrice = source['price']
16
17
18
print(str(active_year) + " " + active_vin + " " + active_make)
19