我正在尝试从 REST API 中提取数据,用 JSON 解析它,然后在 CSV 中添加结果。我遇到的问题是,每次我尝试保存错误时,我得到的是"类型错误:字符串索引必须是整数"。
located_at=curr_loc['located_at']
类型错误:字符串索引必须是整数
这是 API:https://developer.keeptruckin.com/reference#get-current-vehicle-locations
我正在访问的终结点是/vehicle_locations
# -*- coding: utf-8 -*-
import requests
import json
import csv
url='https://api.keeptruckin.com/v1/vehicle_locations'
header={'x-api-key':'API KEY HERE'}
r=requests.get(url,headers=header)
result=r.json()
result = json.loads(r.text)
num_pages=result['pagination']['total']
csvheader=['Number','Date','Time','Location','Lat','Lon','Speed','Bearing','Odometer','Engine Hours']
with open('myfile1.csv', 'a+', newline='') as csvfile:
writer = csv.writer(csvfile, csv.QUOTE_ALL)
##writer.writerow(csvheader)
for veh in result['vehicles']:
number = veh['vehicle']['number']
for curr_loc in veh['vehicle']['current_location']:
located_at=curr_loc['located_at']
date,time=located_at.split['T']
location=curr_loc['description']
lat=curr_loc['lat']
lon=curr_loc['lon']
speed=curr_loc['speed']
bearing=curr_loc['bearing']
engine_hours=curr_loc['engine_hours']
odometer=curr_loc['odometer']
if not location:
location = "N/A"
writer.writerow((number, date,time, location, lat, lon,speed,bearing,odometer,engine_hours))
根据您链接的 API,veh['vehicle']['current_location']
是一个将键映射到字符串值的字典。如果要按名称访问密钥,则不需要for
循环。一种可能性是像这样更改代码:
with open('myfile1.csv', 'a+', newline='') as csvfile:
writer = csv.writer(csvfile, csv.QUOTE_ALL)
##writer.writerow(csvheader)
for veh in result['vehicles']:
number = veh['vehicle']['number']
curr_loc = veh['vehicle']['current_location']:
located_at=curr_loc['located_at']
date,time=located_at.split['T']
location=curr_loc['description']
lat=curr_loc['lat']
lon=curr_loc['lon']
speed=curr_loc['speed']
bearing=curr_loc['bearing']
engine_hours=curr_loc['engine_hours']
odometer=curr_loc['odometer']
if not location:
location = "N/A"
writer.writerow((number, date,time, location, lat, lon,speed,bearing,odometer,engine_hours))