我正在尝试使用BLS API从RCurl
中提取时间序列数据。
BLS为命令行提取提供了以下示例代码:
curl -i -X POST -H 'Content-Type: application/json'
-d '{"seriesid":["LEU0254555900", "APU0000701111"],
"startyear":"2002", "endyear":"2012"}'
http://api.bls.gov/publicAPI/v1/timeseries/data/
我还确认指定的文件(即系列ids)都存在,因为以下两种文件都会产生一个JSON格式的对象:
require(RCurl)
bls.content_test1 <- getURLContent("http://api.bls.gov/publicAPI/v1/timeseries/data/LEU0254555900")
bls.content_test2 <- getURLContent("http://api.bls.gov/publicAPI/v1/timeseries/data/APU0000701111")
基于带有RCurl
标记的各种帖子(特别是这个帖子 ),我将命令行脚本移植到以下代码块:
require(RJSONIO)
jsonbody <- toJSON(list("seriesid"=paste('"["CFU0000008000"', '[LEU0254555900"]"')
,"startyear"="2012"
,"endyear"="2013"))
httpheader <- c(Accept="application/json; charset=UTF-8",
"Content-Type"="application/json")
bls.content <- postForm("http://api.bls.gov/publicAPI/v1/timeseries/data/"
,.opts=list(httpheader=httpheader
,postfields=jsonbody))
产生的结果:
[1] "{\"status\":\"REQUEST_FAILED\",\"responseTime\":0,\"message\":[\"Your request has failed, please check your input parameters and try your request again.\"],\"Results\":null}"
attr(,"Content-Type")
charset
"application/json" "UTF-8"
这似乎是我的RCurl
实现的一个问题,还是这似乎是一个问题的BLS API?
发布于 2014-08-18 15:40:44
实际上,这与您创建json
主体的方式存在问题。如果你用你的版本--如果你做cat(jsonbody)
--你会得到
{
"seriesid": "\"[\"CFU0000008000\" [LEU0254555900\"]\"",
"startyear": "2012",
"endyear": "2013"
}
里面有多余的逃脱器和托架。这不对。相反,试着
jsonbody <- toJSON(list("seriesid"=c("CFU0000008000", "LEU0254555900"),
startyear="2012",
endyear="2013"))
这给
{
"seriesid": [ "CFU0000008000", "LEU0254555900" ],
"startyear": "2012",
"endyear": "2013"
}
这是有效的JSON。只需更改该部分并按照您的要求使用其余的代码,就会给我一条REQUEST_SUCCEEDED消息。
https://stackoverflow.com/questions/25366947
复制相似问题