如何解决使用 Python 访问 JSON 元素
我想访问“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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。