我有这个数据结构,我想通过RJSONIO :: toJSON调用转换为JSON
tmpdf<-data.frame(Date=c("20140610", "20140611"), Users=c(5,10))
tmp<-list(data=tmpdf,
onduplicate=data.frame(Users="replace"),
type=data.frame(Users="line"),
color=data.frame(Users="#52ff7f"))
我需要生成这些数据:
{ "data": [ { "Date": "20140610", "Users": "5"},
{ "Date": "20140611", "Users": "10"} ],
"onduplicate":{ "Users": "replace" },
"color": { "Users": "#52ff7f" },
"type": { "Users": "line" }
}
但是当我使用RJSONIO时
> cat(toJSON(tmp))
我明白了:
{ "data": { "Date": ["20140610", "20140611"], "Users":[5, 10]},
"onduplicate":{"Users":"replace"},
"color": {"Users":"#52ff7f"}
"type": {"Users":"line"},
}
几乎与所需内容相同但数据嵌套出错。这不仅仅是一个小例子。这需要针对数百个数据点进行。 tmpdf模拟的原始数据将始终作为data.frame传递。两个JSON都是有效的JSON,但提供者我推送数据只接受第一种格式。我怎么能这样做?
答案 0 :(得分:1)
tmpdf <- data.frame(Date=c("20140610", "20140611"), Users=c(5,10))
tmpdf <- apply(tmpdf, 1, as.list) #ADDED
tmp <- list(data=tmpdf,
onduplicate=data.frame(Users="replace"),
type=data.frame(Users="line"),
color=data.frame(Users="#52ff7f"))
cat(toJSON(tmp))
给出
{ "data": [ { "Date": "20140610","Users": " 5" },
{ "Date": "20140611","Users": "10" } ],
"onduplicate": { "Users": "replace" },
"type": { "Users": "line" },
"color": { "Users": "#52ff7f" }
}
亲切的问候