Skip to content

Instantly share code, notes, and snippets.

@jnolis
Last active June 30, 2021 02:44
Show Gist options
  • Save jnolis/cb157133c6ea1d45b8210eb091f8d3df to your computer and use it in GitHub Desktop.
Save jnolis/cb157133c6ea1d45b8210eb091f8d3df to your computer and use it in GitHub Desktop.
library(tidyverse)
library(jsonlite)
x <- tribble(
~name, ~city, ~age,
"Heather", "Renton", 31,
"Jacqueline", "Issaquah", 34
)
# BAD WAY
toJSON(x, dataframe = "columns")
# GOOD WAY
# if you have like 100 columns to combine there is a way to do it without writing it out, but it takes longer
x %>%
mutate(person = paste0(name, ", ", city,", ", age)) %>%
select(person) %>%
toJSON()
# JSONL WAY ( this is not the most efficient but it is the closest to)
result <-
x %>%
transpose() %>% # this turns it from a dataframe to a list where each element is a row, which makes this all easier
map_chr(toJSON, auto_unbox=TRUE) %>% # use map to turn each object into json individually, the auto_unbox is like... a thing I can explain over the phone
paste0(collapse="\n") # combine them into a single string with newlines between each
cat(result) # just print it prettier if you are copying and pasting
write_file(result,"temp.jsonl") # if you want to save it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment