1
     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()from将这些文档插入 MongoDB 中RMongo
我一直在玩弄,toJSON()但想不出办法。final$email如上所述,如何在 JSON 文档中进行转换?

4

2 回答 2

2

我认为,您应该首先将 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))
于 2017-04-08T07:28:04.870 回答
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"}]
于 2017-04-08T07:24:09.980 回答