Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Patch the infinite recursion of asJSON on subclasses of vctrs_vctr instances… #438

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

coissac
Copy link

@coissac coissac commented May 22, 2024

Goals of the PR

To answer what I expect to be a better way to #424, I propose the following patch, which changes the asJSON method for the vcrts::vctrs_vctr class.

Principle of the patch

The idea of this patch is to allow people who develop classes derived from the vcrts::vctrs_vctr class to add an S3 method called vec_proxy_json to their class. This follows the same principle implemented in the vctrs package for the comparison operators and ordering operations involving subclasses of vctrs_vctr (i.e., the vec_proxy_compare and vec_proxy_order methods). The method must change the original vector into a new one that can be easily converted into JSON (e.g. a simple character, integer, numeric, or logical vector), or into something more sophisticated if needed, such as a list.

A version of the vec_proxy_json method is implemented for the original vctrs_vctr class. It mimics the original asJSON code for the vcrts::vctrs_vctr class.

Effect of the patch

According to the exchange in issue #424, the bug was introduced as a workaround for issue #408. I have reproduced the example with the patch applied to test if it works as expected.

loadNamespace("posterior") # (>= 1.3.0)
# <environment: namespace:posterior>

x <- structure("a", class = c("vctrs_vctr", "character"))

jsonlite:::asJSON(x)
# [1] "[\"a\"]"

If you create two simple instances of vctrs_vctr, one wrapping an integer vector, the second wrapping a character vector, both will produce the correct json.

z <- vctrs::new_vctr(1:10)

z
# <vctrs_vctr[10]>
#  [1]  1  2  3  4  5  6  7  8  9 10

jsonlite:::asJSON(z)
# [1] "[1,2,3,4,5,6,7,8,9,10]"

zc <- vctrs::new_vctr(as.character(1:10))  

jsonlite:::asJSON(zc)
# [1] "[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\"]"

Hopping that it can help.

All the best

Eric

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant