我正在开发一些函数来从StatBank Denmark 及其API获取数据。他们制作了一个控制台来测试 JSON 调用,并且我知道我在函数 dst_get_data 中解析为 JSON 的 basic_request 有效,因为我已经在控制台中对其进行了测试。
我收到“状态 400”错误和一条错误消息,提示我应该“在发布时提供对象”。
下面的代码应该是可重现的示例。这是我卡住的第三个函数(dst_get_data)。
dst_meta <- function(table, ..., lang = "en"){
require(jsonlite)
require(httr)
dkstat_url <- "http://api.statbank.dk/v1/tableinfo"
params <- list("lang" = lang,
"table" = table,
"format" = "JSON")
meta <- POST(url=dkstat_url, body=params, multipart=FALSE)
meta <- jsonlite::fromJSON(txt=content(meta, as="text"),simplifyDataFrame=TRUE)
#meta <- RJSONIO::fromJSON(content=content(meta),asText=TRUE, simplify=TRUE, simplifyWithNames=TRUE)
return(meta)
}
dst_meta_parse <- function(meta, lang){
basics_names <- c("id", "text", "description",
"unit", "updated", "footnote")
basics <- meta[names(meta) %in% basics_names]
variables <- meta[["variables"]][,c("id", "text")]
values <- meta[["variables"]][,"values"]
names(values) <- variables$id
if(lang == "en"){
test <- grepl(pattern="Tid", names(values))
if(sum(test) > 0){
values$Tid$id <- sub(pattern="Q", replacement="K", x=values$Tid$id)
}
}
## Create basic_request for the data_post file
basic_request <- vector(mode="list", length=length(variables$id))
for(variable in 1:length(variables$id)){
var_name <- variables$id[variable]
if(var_name == "Tid"){
basic_request[[variable]] <- list("code" = var_name,
"values" = as.character(values[[var_name]]$id[length(values[[var_name]]$id)]))
} else {
basic_request[[variable]] <- list("code" = var_name,
"values" = as.character(values[[var_name]]$id[1]))
}
}
return(list("basics" = basics, "variables" = variables, "values" = values, "basic_request" = basic_request))
}
dst_get_data <- function(request, table,..., lang = "en", format = "CSV", value_presentation = "Default"){
require(httr)
require(jsonlite)
dst_url <- "http://api.statbank.dk/v1/data"
final_request <- list("table" = table,
"lang" = lang,
"format" = format,
"valuePresentation" = value_presentation,
"variables" = request)
final_request <- jsonlite::toJSON(x=final_request, .escapeEscapes=TRUE, asIs=TRUE)
print(validate(final_request))
data <- POST(url=dst_url, body=final_request, multipart=FALSE)
return(data)
}
test <- dst_meta(table="folk1")
test2 <- dst_meta_parse(meta = test, lang = "en")
test3 <- dst_get_data(request = test2$basic_request, table = "folk1", format="JSON")
#test3 <- dst_get_data(request = test2$basic_request, table = "folk1", format="JSON")