diff --git a/R/asJSON.AsIs.R b/R/asJSON.AsIs.R new file mode 100644 index 0000000..06951f3 --- /dev/null +++ b/R/asJSON.AsIs.R @@ -0,0 +1,14 @@ +setOldClass("AsIs") +setMethod("asJSON", "AsIs", function(x, auto_unbox = FALSE, ...) { + + # Strip off the AsIs class so we can dispatch to other asJSON methods. + class(x) <- setdiff(class(x), "AsIs") + + if (is.atomic(x) && length(x) == 1) { + # Never auto_unbox single values when wrapped with I() + asJSON(x, auto_unbox = FALSE, ...) + + } else { + asJSON(x, auto_unbox = auto_unbox, ...) + } +}) diff --git a/inst/tests/test-toJSON-AsIs.R b/inst/tests/test-toJSON-AsIs.R new file mode 100644 index 0000000..f476343 --- /dev/null +++ b/inst/tests/test-toJSON-AsIs.R @@ -0,0 +1,14 @@ +context("toJSON AsIs") + +test_that("Encoding AsIs", { + expect_that(toJSON(list(1), auto_unbox=TRUE), equals("[1]")); + expect_that(toJSON(list(I(1)), auto_unbox=TRUE), equals("[[1]]")); + expect_that(toJSON(I(list(1)), auto_unbox=TRUE), equals("[1]")); + + expect_that(toJSON(list(x=1)), equals("{\"x\":[1]}")); + expect_that(toJSON(list(x=1), auto_unbox=TRUE), equals("{\"x\":1}")); + expect_that(toJSON(list(x=I(1)), auto_unbox=TRUE), equals("{\"x\":[1]}")); + + expect_that(toJSON(list(x=I(list(1))), auto_unbox=TRUE), equals("{\"x\":[1]}")); + expect_that(toJSON(list(x=list(I(1))), auto_unbox=TRUE), equals("{\"x\":[[1]]}")); +});