email foo bar
1 a@g.com 23 34
2 b@g.com 43 34
3 c@g.com 35 32
现在,我想为以下表单的每封电子邮件创建JSON文档:
doc 1:{ "email" : "a@g.com"}
doc 2:{ "email" : "b@g.com"}
doc 3:{ "email" : "c@g.com"}
我的最终目标是使用dbInsertDocument()
中的RMongo
在MongoDB中插入这些文档。
我一直在玩toJSON()
,但无法找到方法。如何在JSON文档中转换final$email
,如上所述?
答案 0 :(得分:1)
我认为,您应该首先将data.frame转换为列表列表:
## basically you split your data.frame by row
## for each row you convert it as a list
LMAo <- unname(lapply(split(dx,seq_len(nrow(dx))), function(x) as.list(x)))
## auto unboxing to no treat scalar as vector
jsonlite::toJSON(LMAo,auto_unbox = T)
[
{"email":"a@g.com","foo":23,"bar":34},
{"email":"b@g.com","foo":43,"bar":34},
{"email":"c@g.com","foo":35,"bar":32}
]
## same result using RJSONIO
cat(RJSONIO::toJSON(LMAo))
答案 1 :(得分:0)
我不确定这是否是您所需要的:
final$email
没有列名,因此它不包含在toJSON(final$email)
library(jsonlite)
txt <- "email foo bar
1 a@g.com 23 34
2 b@g.com 43 34
3 c@g.com 35 32"
final <- read.table(text=txt, stringsAsFactors = FALSE)
toJSON(final$email)
# [1] "[\"a@g.com\",\"b@g.com\",\"c@g.com\"]"
# final$email has to be converted to data.frame
dt <- data.frame(final$email)
colnames(dt) <- "email"
toJSON(dt)
# [{"email":"a@g.com"},{"email":"b@g.com"},{"email":"c@g.com"}]