R:将 python 词典 json 解析为 xts
R: parse python dictionary over json into xts
我创建一些xts对象,将它们保存为csv文件,上传到google云平台,...,创建一个Python字典,下载字典并得到结果(几个原始文件一次通过 REST API) 使用 Rcurl 返回 R。
我想重新创建原来的 xts 对象,但无法正确解析最终结果。
这里是数据流:
其中一个 csv 文件如下所示(它们都具有相同的结构):
R 中的结果取自:
library(RCurl)
all_files <- getURL("https://....")
all_parsed <- jsonlite::fromJSON(all_files)
,是一个列表,看起来像:
如果我用 cat(all_parsed$2020-09-24.csv
) 打印结果,它的结构正好适合 xts:
但由于\n \"等问题,我无法真正使用这些数据
我可以用 strsplit(...) 尝试一下,但工作量很大。
有没有更好的解析结果的方法?
抱歉,我无法提供更好的 explanations/reproducible 代码 - 我可以通过邮件将 Rcurl 的 URL 发送给你们中的一些人。
谢谢!
像这样?
library(stringr)
# Example string
ex_str <- "\"Index\",\"E2202\"\n\"2020-09-04\",NA\n\"2020-12-02\",2.7"
# First, split on the \n which represents a new line
ex_str <- str_split(ex_str, "\n")[[1]]
# Then, drop quotation marks
str_replace_all(ex_str, "\"", "")
[1] "Index,E2202" "2020-09-04,NA" "2020-12-02,2.7"
好的,谢谢。我将完成您的代码:
eex_str <- str_replace_all(ex_str, "\"", "")[-length(str_replace_all(ex_str, "\"", ""))]
index_string <- unlist(str_split(eex_str, ","))[c(TRUE,FALSE)] #
data_string <- unlist(str_split(eex_str, ","))[c(FALSE,TRUE)] # both length 6
library(xts)
suppressWarnings(recreated_xts <- xts(x = as.numeric(data_string[-1]), order.by = as.Date(index_string[-1] ))) # supress NAs introduced by coercion
colnames(recreated_xts) <- data_string[1]
recreated_xts
我创建一些xts对象,将它们保存为csv文件,上传到google云平台,...,创建一个Python字典,下载字典并得到结果(几个原始文件一次通过 REST API) 使用 Rcurl 返回 R。
我想重新创建原来的 xts 对象,但无法正确解析最终结果。
这里是数据流:
其中一个 csv 文件如下所示(它们都具有相同的结构):
R 中的结果取自:
library(RCurl)
all_files <- getURL("https://....")
all_parsed <- jsonlite::fromJSON(all_files)
,是一个列表,看起来像:
如果我用 cat(all_parsed$2020-09-24.csv
) 打印结果,它的结构正好适合 xts:
但由于\n \"等问题,我无法真正使用这些数据
我可以用 strsplit(...) 尝试一下,但工作量很大。
有没有更好的解析结果的方法?
抱歉,我无法提供更好的 explanations/reproducible 代码 - 我可以通过邮件将 Rcurl 的 URL 发送给你们中的一些人。
谢谢!
像这样?
library(stringr)
# Example string
ex_str <- "\"Index\",\"E2202\"\n\"2020-09-04\",NA\n\"2020-12-02\",2.7"
# First, split on the \n which represents a new line
ex_str <- str_split(ex_str, "\n")[[1]]
# Then, drop quotation marks
str_replace_all(ex_str, "\"", "")
[1] "Index,E2202" "2020-09-04,NA" "2020-12-02,2.7"
好的,谢谢。我将完成您的代码:
eex_str <- str_replace_all(ex_str, "\"", "")[-length(str_replace_all(ex_str, "\"", ""))]
index_string <- unlist(str_split(eex_str, ","))[c(TRUE,FALSE)] #
data_string <- unlist(str_split(eex_str, ","))[c(FALSE,TRUE)] # both length 6
library(xts)
suppressWarnings(recreated_xts <- xts(x = as.numeric(data_string[-1]), order.by = as.Date(index_string[-1] ))) # supress NAs introduced by coercion
colnames(recreated_xts) <- data_string[1]
recreated_xts