【问题标题】:Using RCurl postForm to gather JSON data使用 RCurl postForm 收集 JSON 数据
【发布时间】:2014-08-18 15:32:28
【问题描述】:

我正在尝试使用RCurlBLS API 中提取时间序列数据。

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/ 

我还确认指定的文件(即系列 ID)都存在,因为以下两者都产生 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 标签(尤其是post)的各种帖子,我已将命令行脚本移植到以下代码块中:

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 的问题?

【问题讨论】:

    标签: r curl rcurl


    【解决方案1】:

    这实际上是您创建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 消息。

    【讨论】:

      【解决方案2】:

      这是一个使用 httr 的方法:

      library(httr)
      library(jsonlite)
      
      # Need unbox() to tell jsonlite() numbers are scalars, not vectors of length 1
      body <- list(
        seriesid = c("CFU0000008000", "LEU0254555900"),
        startyear = unbox(2012),
        endyear = unbox(2013)
      )
      
      r <- POST("http://api.bls.gov/publicAPI/v1/timeseries/data/", body = body, encode = "json")
      stop_for_status(r)
      
      # Need to specify type since site returns incorrect type of text/plain
      str(content(r, type = "application/json"))
      

      【讨论】:

        猜你喜欢
        • 2023-03-11
        • 1970-01-01
        • 2014-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多