StefanG
StefanG

Reputation: 1264

Add JSON column to R dataframe

I have a data frame and want to add an additional column that contains the data per row in JSON format. In this example:

dfr = data.frame(name = c("Andrew", "Mathew", "Dany", "Philip", "John", "Bing", "Monica"), age = c(28, 23, 49, 29, 38, 23, 29))

dfr %>% mutate(Payload = jsonlite::toJSON(dfr))

I would like to get

Andrew  28   {"name":"Andrew","age":28}
Mathew  23   {"name":"Mathew","age":23}

Instead I get per row the JSON string for the complete data frame. I tried it with apply but I fail to get it to run.

Upvotes: 3

Views: 315

Answers (1)

zx8754
zx8754

Reputation: 56219

Try running per each row: split every row, then apply toJSON function:

dfr$Payload <- sapply(split(dfr, seq(nrow(dfr))), toJSON)

dfr
#     name age                      Payload
# 1 Andrew  28 [{"name":"Andrew","age":28}]
# 2 Mathew  23 [{"name":"Mathew","age":23}]
# 3   Dany  49   [{"name":"Dany","age":49}]
# 4 Philip  29 [{"name":"Philip","age":29}]
# 5   John  38   [{"name":"John","age":38}]
# 6   Bing  23   [{"name":"Bing","age":23}]
# 7 Monica  29 [{"name":"Monica","age":29}]

Upvotes: 4

Related Questions