How to convert column of a data frame in json format in R

1.3k Views Asked by At
     email    foo    bar  
1  [email protected]    23     34  
2  [email protected]    43     34  
3  [email protected]    35     32

Now I want to create JSON docs for each email as of following form:
doc 1: { "email" : "[email protected]"}
doc 2: { "email" : "[email protected]"}
doc 3: { "email" : "[email protected]"}

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?

2

There are 2 best solutions below

0
Enrique Pérez Herrero On

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 [email protected] 23 34
2 [email protected] 43 34
3 [email protected] 35 32"

final <- read.table(text=txt, stringsAsFactors = FALSE)
toJSON(final$email)
# [1] "[\"[email protected]\",\"[email protected]\",\"[email protected]\"]"    

# final$email has to be converted to data.frame
dt <- data.frame(final$email)
colnames(dt) <- "email"
toJSON(dt)
# [{"email":"[email protected]"},{"email":"[email protected]"},{"email":"[email protected]"}]
0
agstudy On

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":"[email protected]","foo":23,"bar":34},
  {"email":"[email protected]","foo":43,"bar":34},
  {"email":"[email protected]","foo":35,"bar":32}
] 

## same result using RJSONIO
 cat(RJSONIO::toJSON(LMAo))