Search code examples
rjsondataframeplumber

change the format of json serialization for R dataframe in plumber api


I have a data frame in R that i want to serialize into json in a particular format. Sample code:

df_t<-data.frame(c(453:458),c(1:6), row.names = NULL)
colnames(df_t) <- c("area", "price")
jsonlite::toJSON(df_t)

The format of output of above code is as below:

[{"area":453,"price":1},{"area":454,"price":2},{"area":455,"price":3},{"area":456,"price":4},{"area":457,"price":5},{"area":458,"price":6}]

But the format I want is:

{"area":[453,454,455,456,457,458],"price":[1,2,3,4,5,6]}

To get the format I require i have written this bit of code which gives me similar output to what i expect but enclosed in quotes:

paste0( '{', colnames(df_t)[1], ':', jsonlite::toJSON(df_t[,1]),  ',', colnames(df_t)[2], ':', jsonlite::toJSON(df_t[,2]), '}')

"{area:[453,454,455,456,457,458],price:[1,2,3,4,5,6]}"

My question is that is there a better way to get the format I want? The dataframe is being returned from a R plumber api and so is using jsonlite serializer by default.


Solution

  • json and the jsonlite package lend themselves more readily to the list format. It could be that altering the default serialization is more work than simply converting the R data structure to match.

    I would suggest something along the lines of

    df_t<-data.frame(c(453:458),c(1:6), row.names = NULL)
    colnames(df_t) <- c("area", "price")
    
    df_t_list <- list()
    for(i in 1:ncol(df_t)) {
      df_t_list[[i]] <- df_t[ , i]
    }
    names(df_t_list) <- c("area", "price")
    
    jsonlite::toJSON(df_t_list)