0

I want to use purrr::map() to append a new column to a list of json files containing a table with an id variable as an identifier.

I read the files this way:

path <- "my_path"
files <- dir(path, pattern = "*.json")

data <- files %>%
        map(~fromJSON(file.path(path, .), flatten = TRUE)

data <- data %>%
     mutate(new_var = //do something//)

Then, I would like to take this new variable and append it to the list of json files with the id variable using a purrr map type approach.

Is there a way to do this?

tyluRp
  • 4,678
  • 2
  • 17
  • 36
Monduiz
  • 711
  • 10
  • 22

1 Answers1

0

You're almost there.

Your "add" new variable needs to be done using map as well, since your data is potentially a list of dataframes.

library(tidyverse)
library(jsonlite)

json <-
  '[
  {"Name" : "Mario", "Age" : 32, "Occupation" : "Plumber"}, 
  {"Name" : "Peach", "Age" : 21, "Occupation" : "Princess"},
  {},
  {"Name" : "Bowser", "Occupation" : "Koopa"}
]'


json2 <-
  '[
  {"Name" : "Luigi", "Age" : 31, "Occupation" : "Plumber"}, 
  {"Name" : "Toad", "Age" : 32, "Occupation" : "Majordomo"},
  {},
  {"Name" : "Koopa", "Occupation" : "Henchman"}
]'


list(json, json2) %>% 
  map(~fromJSON(.x)) %>% 
  map(~mutate(.x, Game = "Super Mario Bros")) 

[[1]]
    Name Age Occupation             Game
1  Mario  32    Plumber Super Mario Bros
2  Peach  21   Princess Super Mario Bros
3   <NA>  NA       <NA> Super Mario Bros
4 Bowser  NA      Koopa Super Mario Bros

[[2]]
   Name Age Occupation             Game
1 Luigi  31    Plumber Super Mario Bros
2  Toad  32  Majordomo Super Mario Bros
3  <NA>  NA       <NA> Super Mario Bros
4 Koopa  NA   Henchman Super Mario Bros

If your json is more complex, I suggest reading the vignettes for jsonlite and reading this post

Jake Kaupp
  • 7,892
  • 2
  • 26
  • 36