1

I am trying to use the function toJSON from the library jsonlite in R to transform a dataframe into json, however the formats that it returns by default are not suitable for me.

Considering the following example:

df <- data.frame(id = c(1,2), val1 = c("A", "B"), val2 = c("C", "D"))

If I use toJSON(df), here's what I get:

[{"id":1,"val1":"A","val2":"C"},{"id":2,"val1":"B","val2":"D"}] 

Instead what I want is as close as possible to this:

[
  "1": {"val1":"A","val2":"C"},
  "2":{"val1":"B","val2":"D"}
] 

How can I transform df in a way that I can accomplish it? Just to be clear, my case has a very long dataframe with additional columns. I want the value of one specific column to be the key to the rest of the row.

Thanks!

1 Answer 1

2

An option is to split by 'id' and then apply toJSON

library(jsonlite)
toJSON(split(df[-1], df$id))

If we want to remove the []

gsub("[][]", "", toJSON(split(df[-1], df$id)))
#{"1":{"val1":"A","val2":"C"},"2":{"val1":"B","val2":"D"}} 
Sign up to request clarification or add additional context in comments.

2 Comments

Nice! Can I get rid of the list thought? I got {"1":[{"val1":"A","val2":"C"}],"2":[{"val1":"B","val2":"D"}]}
@JoséLuizFerreira Try with auto_unbox = TRUE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.