diff --git a/R/json.R b/R/json.R index 58bf4a9..13fdd4d 100644 --- a/R/json.R +++ b/R/json.R @@ -40,7 +40,12 @@ orbital_json_write <- function(x, path) { actions <- as.list(unclass(x)) - res <- list(actions = actions, version = 1) + res <- list( + actions = actions, + pred_names = attr(x, "pred_names"), + version = 2 + ) + res <- jsonlite::toJSON(res, pretty = TRUE, auto_unbox = TRUE) writeLines(res, path) @@ -85,9 +90,17 @@ orbital_json_write <- function(x, path) { orbital_json_read <- function(path) { rlang::check_installed("jsonlite") - res <- jsonlite::read_json(path) + json <- jsonlite::read_json(path) + + version <- json$version - res <- unlist(res$actions) + if (version == 1) { + res <- unlist(json$actions) + attr(res, "pred_names") <- utils::tail(names(res), 1) + } else if (version == 2) { + res <- unlist(json$actions) + attr(res, "pred_names") <- json$pred_names + } new_orbital_class(res) } diff --git a/tests/testthat/test-json.R b/tests/testthat/test-json.R index a21f88a..9321a59 100644 --- a/tests/testthat/test-json.R +++ b/tests/testthat/test-json.R @@ -20,8 +20,37 @@ test_that("read and write json works", { new <- orbital_json_read(tmp_file) - # temp fix - attr(orbital_obj, "pred_names") <- NULL + expect_identical(new, orbital_obj) +}) + +test_that("read and write json works - backwards from version 1", { + skip_if_not_installed("recipes") + skip_if_not_installed("tidypredict") + skip_if_not_installed("jsonlite") + skip_if_not_installed("workflows") + rec_spec <- recipes::recipe(mpg ~ ., data = mtcars) %>% + recipes::step_normalize(recipes::all_numeric_predictors()) + + lm_spec <- parsnip::linear_reg() + + wf_spec <- workflows::workflow(rec_spec, lm_spec) + + wf_fit <- parsnip::fit(wf_spec, mtcars) + + orbital_obj <- orbital(wf_fit) + + tmp_file <- tempfile() + + orbital_json_write(orbital_obj, tmp_file) + + # Fake version 1 + fake_json <- jsonlite::read_json(tmp_file) + fake_json$pred_names <- NULL + fake_json$version <- 1 + fake_json <- jsonlite::toJSON(fake_json, pretty = TRUE, auto_unbox = TRUE) + writeLines(fake_json, tmp_file) + + new <- orbital_json_read(tmp_file) expect_identical(new, orbital_obj) })