json - 如何以更简洁的方式将 JSON 格式的请求从 R 中的 URL 获取 JSON 数据发送到 data.frame 中?

标签 json r web-services api rcurl

我在 R 中编写了以下代码以开始使用数据请求 API。这是一个普通的网络服务 JSON API。

library(RJSONIO)
library(RCurl)
library(httr)

r <- POST("http://api.scb.se/OV0104/v1/doris/sv/ssd/START/PR/PR0101/PR0101A/KPIFastM2", 
          body = '{ "query": [], "response": { "format": "json" } }')
stop_for_status(r)
a<-content(r, "text", "application/json", encoding="UTF-8")
cat(a, file = "test.json")
x<-fromJSON(file("test.json", "r"))
mydf<-do.call(rbind, lapply(x$data, data.frame))
colnames(mydf)<-c("YearMonth", "CPI")

基本上,它使用 httr 为 URL 初始化一个 get reuest,然后通过 fromJSON 将生成的 JSON 数据转换为 R 结构。 JSON 请求如下所示:

{ "query": [], "response": { "format": "json" } }

事实上,我的代码确实像我希望的那样将数据放入 data.frame 中,但它冗长得令人痛苦,我拒绝相信所有这些行都是实现所需结果所必需的。想要的结果当然是 mydf data.frame。

那么我的问题是:从 Web 服务获取数据到 data.frame 的最短和最正确的方法是什么?

干杯, 迈克尔

最佳答案

有两个问题。一个是您没有使用 jsonlite :-) 另一个是您的 JSON 源似乎在 blob 前加上了 U+FEFF Byte order Mark使 JSON 无效的字符。 RFC7159说:

Implementations MUST NOT add a byte order mark to the beginning of a JSON text. In the interests of interoperability, implementations that parse JSON texts MAY ignore the presence of a byte order mark rather than treating it as an error.

所以 scb.se 没有正确格式化他们的 JSON。无论哪种方式,试试这个:

library(jsonlite)
library(httr)

req <- POST("http://api.scb.se/OV0104/v1/doris/sv/ssd/START/PR/PR0101/PR0101A/KPIFastM2", 
  body = '{ "query": [], "response": { "format": "json" } }')
stop_for_status(req)
json <- content(req, "text")


# JSON starts with an invalid character:
validate(json)
json <- substring(json, 2)
validate(json)

# Now we can parse
object <- jsonlite::fromJSON(json)
print(objects)

关于json - 如何以更简洁的方式将 JSON 格式的请求从 R 中的 URL 获取 JSON 数据发送到 data.frame 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26693842/

相关文章:

c# - 通过网络序列化对象

web-services - 从 WCF 项目返回有意义的异常

json - 使用 XQuery 检查 XML 文档的命名空间前缀是否在整个文件中被重新定义

ios - 在 Swift 中将 JSON 字符串转换为 Object 的简单而干净的方法

r - 为什么R中的fuzzyjoin比data.table慢

按组保留行,直到在列中首次出现值为止。没有值(value)的团体

ios - Parse.com - JSON 导入日期字段错误

ios - 如何获取json数据并通过segue传递它

r - 从每个案例的创建时间开始计算未结案例的更有效方法

c# - 如何使 C# Web 服务生成 soapenv 命名空间而不是 soap?