unbox: Unbox a vector or data frame

Description Usage Arguments Details Value References Examples

View source: R/unbox.R

Description

This function marks an atomic vector or data frame as a singleton, i.e. a set with exactly 1 element. Thereby, the value will not turn into an array when encoded into JSON. This can only be done for atomic vectors of length 1, or data frames with exactly 1 row. To automatically unbox all vectors of length 1 within an object, use the auto_unbox argument in toJSON.

Usage

1
unbox(x)

Arguments

x

atomic vector of length 1, or data frame with 1 row.

Details

It is usually recommended to avoid this function and stick with the default encoding schema for the various R classes. The only use case for this function is if you are bound to some specific predefined JSON structure (e.g. to submit to an API), which has no natural R representation. Note that the default encoding for data frames naturally results in a collection of key-value pairs, without using unbox.

Value

Returns a singleton version of x.

References

https://en.wikipedia.org/wiki/Singleton_(mathematics)

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
toJSON(list(foo=123))
toJSON(list(foo=unbox(123)))

# Auto unbox vectors of length one:
x = list(x=1:3, y = 4, z = "foo", k = NULL)
toJSON(x)
toJSON(x, auto_unbox = TRUE)

x <- iris[1,]
toJSON(list(rec=x))
toJSON(list(rec=unbox(x)))

Example output

{"foo":[123]} 
{"foo":123} 
{"x":[1,2,3],"y":[4],"z":["foo"],"k":{}} 
{"x":[1,2,3],"y":4,"z":"foo","k":{}} 
{"rec":[{"Sepal.Length":5.1,"Sepal.Width":3.5,"Petal.Length":1.4,"Petal.Width":0.2,"Species":"setosa"}]} 
{"rec":{"Sepal.Length":5.1,"Sepal.Width":3.5,"Petal.Length":1.4,"Petal.Width":0.2,"Species":"setosa"}} 

jsonlite documentation built on Sept. 7, 2020, 9:07 a.m.