Milan
Milan

Reputation: 35

Converting R data frame to JSON while separating each row into a new JSON object

I have an R dataframe that I want to convert to JSON but I want to have each row inserted into the new JSON object named "traits". I've tried to cbind a traits column as the first column and convert the new dataframe to JSON but that doesn't produce the correct output. I've also tried to append a "traits" : { object to each converted JSON output but that also failed. I'm trying to work within the dataframe then convert it to JSON because toJSON produces a list in brackets [], which I cant' get around either.I'm using jsonlite

color = c('red','blue','green')
fruit = c('apple','orange','grape')
animal = c('cat','dog','chicken')
df<- data.frame(color, fruit, animal)
toJSON(df, pretty= TRUE)

I want it to look like this:

[
  { "traits": {
      "color": "red",
      "fruit": "apple",
      "animal": "cat"
  }
    },

Upvotes: 2

Views: 1615

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

Here is a way:

L <- list(list(traits = as.list(df[1,])), 
          list(traits = as.list(df[2,])),
          list(traits = as.list(df[3,])))

> toJSON(L, pretty = TRUE, auto_unbox = TRUE)
[
  {
    "traits": {
      "color": "red",
      "fruit": "apple",
      "animal": "cat"
    }
  },
  {
    "traits": {
      "color": "blue",
      "fruit": "orange",
      "animal": "dog"
    }
  },
  {
    "traits": {
      "color": "green",
      "fruit": "grape",
      "animal": "chicken"
    }
  }
] 

To get this list L you can do

L <- apply(df, 1, function(x) list(traits = as.list(x)))

Another way is:

df2 <- purrr::transpose(lapply(df, function(x) as.character(x)))
L <- lapply(df2, function(x) list(traits = x))

or

df <- data.frame(color, fruit, animal, stringsAsFactors = FALSE)
L <- lapply(purrr::transpose(df), function(x) list(traits = x))

Upvotes: 2

Related Questions