我试图将多个vin number粘贴到nthsa API。
我的工作解决方案如下所示:
vins <- c('4JGCB5HE1CA138466','4JGCB5HE1CA138466','4JGCB5HE1CA138466','4JGCB5HE1CA138466','4JGCB5HE1CA138466','4JGCB5HE1CA138466','4JGCB5HE1CA138466','4JGCB5HE1CA138466','4JGCB5HE1CA138466','4JGCB5HE1CA138466','4JGCB5HE1CA138466',)
for (i in vins){
json <- fromJSON(paste0('https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/',i,'?format=json'))
print(json)
}
这个解决方案非常慢。我尝试了pbapply,同样的事情,因为它一次粘贴一个vin。
有一个我无法弄清楚的批量粘贴选项。有人可以帮忙吗?
这是我到目前为止的代码:
data <- list(data='4JGCB5HE1CA138466;4JGCB5HE1CA138466;4JGCB5HE1CA138466;4JGCB5HE1CA138466')
json <- toJSON(list(data=data), auto_unbox = TRUE)
result <- POST('https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/', body = data)
Output <- content(result)
vin 编号字符串必须采用以下格式:vin;文;文;文;
这是链接:https://vpic.nhtsa.dot.gov/api/(最后一个(
提前谢谢。
更新:
我也从其他一些线程中尝试过这个,但没有运气:
headers = c(
`Content-Type` = 'application/json'
)
data = '[{"data":"4JGCB5HE1CA138466;4JGCB5HE1CA138466;4JGCB5HE1CA138466;4JGCB5HE1CA138466"}]'
httr::POST(url = 'https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/', httr::add_headers(.headers=headers), body = data)
print(r$status_code)
我收到状态代码 200,但服务器代码 500 没有数据。
我不确定这是否可能。批处理终结点专门查找要传递的字典(排除字符串表示形式(。httr
指出:
正文:必须为空、假、字符、原始或列表
我尝试使用collections
库生成字典
data <- Dict$new(list(format = 'json', data = "4JGCB5HE1CA138466;4JGCB5HE1CA138466;4JGCB5HE1CA138466"))
httr
毫不奇怪地拒绝了它,因为它是错误的身体ype。
我尝试使用 jsonlite 进行转换:
data <- jsonlite::toJSON(data)
屈服:
Error: No method asJSON S3 class: R6
我认为由于数据是一种environment
.
尝试在字符串字典中读取 json 返回no data
:
library(httr)
library(jsonlite)
headers = c(
'Accept' = '*/*',
'Accept-Encoding' = 'gzip, deflate',
'Content-Type' = 'application/x-www-form-urlencoded',
'User-Agent' = 'Mozilla/5.0'
)
data = jsonlite::toJSON('{"format":"json","data":"4JGCB5HE1CA138466;4JGCB5HE1CA138466;4JGCB5HE1CA138466"}')
r<- httr::POST(url = 'https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/', httr::add_headers(.headers=headers), body = data. encode='json'
print(content(r))
如果我们检查转换后的数据
> data
["{"format":"json","data":"4JGCB5HE1CA138466;4JGCB5HE1CA138466;4JGCB5HE1CA138466"}"]
这不再是服务器期望的字典结构。
所以,我是R的新手,但似乎使用Python可能更容易,Python有一个字典对象和一个json库,可以舒适地处理转换
字符串到 json:
import requests,json
url = 'https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/'
data = json.loads('{"format": "json", "data":"4JGCB5HE1CA138466;4JGCB5HE1CA138466;4JGCB5HE1CA138466"}')
r = requests.post(url, data=data)
print(r.json())
字典
import requests
url = 'https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/'
data = {'format': 'json', 'data':'4JGCB5HE1CA138466;4JGCB5HE1CA138466;4JGCB5HE1CA138466'}
r = requests.post(url, data=data).json()
print(r)