From 313389fb86fb705d97318085f9d743b94f16966e Mon Sep 17 00:00:00 2001 From: Winston Chang Date: Tue, 17 Mar 2015 15:41:29 -0500 Subject: [PATCH] Add asJSON.AsIs method. Fixes #78 --- R/asJSON.AsIs.R | 14 ++++++++++++++ inst/tests/test-toJSON-AsIs.R | 14 ++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 R/asJSON.AsIs.R create mode 100644 inst/tests/test-toJSON-AsIs.R 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]]}")); +});