Skip to content

Commit

Permalink
Add asJSON.AsIs method. Fixes #78
Browse files Browse the repository at this point in the history
  • Loading branch information
wch committed Mar 17, 2015
1 parent ada25c5 commit 313389f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
14 changes: 14 additions & 0 deletions R/asJSON.AsIs.R
Original file line number Diff line number Diff line change
@@ -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, ...)
}
})
14 changes: 14 additions & 0 deletions inst/tests/test-toJSON-AsIs.R
Original file line number Diff line number Diff line change
@@ -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]]}"));
});

0 comments on commit 313389f

Please sign in to comment.