1
     email    foo    bar  
1  a@g.com    23     34  
2  b@g.com    43     34  
3  c@g.com    35     32

Now I want to create JSON docs for each email as of following form:
doc 1: { "email" : "a@g.com"}
doc 2: { "email" : "b@g.com"}
doc 3: { "email" : "c@g.com"}

My final goal is to insert these docs in MongoDB using dbInsertDocument() from RMongo.
I have been toying with toJSON() but couldn't figure out a way. How do I convert final$email in JSON docs as described above?

rootkea
  • 1,474
  • 2
  • 12
  • 32
  • Can you please check the answers below and accept one of them if you are happy with theem or at least clarify your question? – agstudy Apr 25 '17 at 19:33

2 Answers2

2

I think , you should first convert your data.frame to a list of lists:

## 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))
agstudy
  • 119,832
  • 17
  • 199
  • 261
0

I'm not sure if this is what you need: final$email has not column name so it is not included in the output of 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"}]
Enrique Pérez Herrero
  • 3,699
  • 2
  • 32
  • 33