skip to Main Content

hi i’m trying to convert and R tibble in a shiny app to a json.
i can use jsonlite::toJSON() to do this
unfortunately the receipient requires the output in a different order.
i’ve tried converting the input from long to wide but this comes out all wrong.

the python code to create the json uses

df.to_dict(orient="list")

so i need an r equivalent.

not much experience with json and in a little hurry so help much appreciated

2

Answers


  1. library(dplyr)
    library(jsonlite)
    
    #Sample tibbble
    tibble <- data.frame(col1 = 1:3, col2 = letters[1:3], col3 = c("x", "y", "z"))
    
    #You can change the order with this
    # tibble_reordered <- tibble %>% select(desired_order)
    
    #Convert tibble to list of named vectors
    tibble_list <- as.list(tibble) #Use tibble_reordered if you reordered it
    tibble_list <- lapply(tibble_list, as.vector)
    names(tibble_list) <- names(tibble)  # Set column names as keys
    
    #Convert list to JSON
    json_output <- toJSON(tibble_list, auto = FALSE)
    
    cat(json_output)
    
    Login or Signup to reply.
  2. If @Æsad has the right end goal, then CRAN package rjsoncons

    rjsoncons::j_pivot(tibble)
    

    gets you there, too.

    > j_pivot(tibble) |> noquote()
    [1] {"col1":[1,2,3],"col2":["a","b","c"],"col3":["x","y","z"]}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search