Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write multiple dataframes to same json object

Tags:

r

Using jsonlite package I am able to write a dataframe to json e.g.

library(jsonlite)
library(tidyverse)

mtcars %>% toJSON() %>% write('data/mtcars.json')
diamonds %>% toJSON() %>% write('data/diamonds.json')

My question is, is it possible to add both mtcars and diamonds to the same json object?

like image 965
Doug Fir Avatar asked Jul 26 '26 07:07

Doug Fir


1 Answers

Yes: put the datasets in a list before serializing to JSON:

library(jsonlite)

datasets <- list(datasets = list(mtcars = mtcars, iris = iris))
write(toJSON(datasets), "datasets.json")

This will result in a JSON file with a structure like:

{
  "datasets": {
    "mtcars": [...],
    "iris": [...]
  }
} 
like image 141
Mikko Marttila Avatar answered Jul 28 '26 19:07

Mikko Marttila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!