【发布时间】:2016-12-06 15:24:57
【问题描述】:
第一次发帖,潜伏已久。要温柔。中度 R 用户。我确信有一种更好、更实用的方法来做我需要的事情,但感觉就像我研究过没有洞察力的死亡。
我正在尝试将数据集合并到预先存在的 JSON 结构。许多序列化 JSON 请求的每个 JSON 结构都有一行记录。
我将数据集加载到包含 13 个变量的数据中,并更改列标题以匹配它们在 JSON 结构中的显示方式
library(jsonlite)
#### Map Column headers to their respective names in the JSON Structure
colnames(data) <- c("default.A",
"default.B",
"default.C",
"items.A",
"items.B.1",
"items.B.2",
"items.B.3",
"items.B.4",
)
创建空白 JSON 结构。这是 JSON 请求需要处理的格式。简单的嵌套结构。
sample <- '{
"default": {
"A": "",
"B": "",
"C": "",
},
"items": [{
"A": "",
"B": {
"1": "",
"2": "",
"3": "",
"4": "",
}
}]
}'
jsonstructure <- fromJSON(sample)
将所有内容设置为 DF。合并它们。用空白填充NAs
x <- as.data.frame(data)
y <- as.data.frame(jsonstructure)
Z <- merge(x, y, all = TRUE)
Z[is.na(Z)] <- ""
转换为 JSON
jsonZ <- toJSON(unname(split(Z, 1:nrow(Z))), pretty=TRUE)
cat(jsonZ)
当前输出不匹配
[
[
{
"default.A": "",
"default.B": "1234567890",
"default.C": "",
"items.A": "1234567890",
"items.B.1": "1234",
"items.B.2": "1234",
"items.B.3": "1234",
"items.B.4": "1234",
}
],
[
{
"default.A": "",
"default.B": "0987654321",
"default.C": "",
"items.A": "0987654321",
"items.B.1": "4321",
"items.B.2": "4321",
"items.B.3": "4321",
"items.B.4": "4321",
}
]
]
【问题讨论】: