how to drop empty cells when export to json?

I would like to remove NA and Null from the file when exporting object to json file in R!


library(tibble)

df <- tibble::tribble(~colA, ~colB,~colC,
                      "a",   1, data.frame(x = 1, y = 3), 
                      "b",   2, NA_character_, 
                      "c",   3, NULL, 
)

jsonlite::toJSON(df, dataframe = "rows", pretty = TRUE) %>% 
  write("test.json")

This is what I get
image

This is what i desire to reduce file size.
image

library(tibble)
library(jsonlite)
library(purrr)
library(rlang)
library(shiny) # for the convenience of isTruthy ; but you can replace with your own NULL / NA checking code.
df <- tibble::tribble(
  ~colA, ~colB, ~colC,
  "a", 1, list(data.frame(x = 1, y = 3)),
  "b", 2, NA_character_,
  "c", 3, NULL
)

(rowwise_list <- apply(df, 1, as.list))

rowwwise_list_cleaned <- map(rowwise_list, \(r){
  discard(map(r, \(x)if (shiny::isTruthy(x)) { # see earlier comment on shiny
    x
  } else {
    zap()
  }), is_zap)
})

jsonlite::toJSON(rowwwise_list_cleaned, pretty = TRUE, auto_unbox = TRUE)