I am trying to encode R lists into json using the jsonlite package and the toJSON function. I have a simple item like:
list(op='abc')
I'd like that to become:
{
"op" : "abc"
}
Instead, I get:
{
"op" : ["abc"]
}
The API to which I am trying to feed this json chokes on the latter and requires the former. Any suggestions on how to get the former behavior from jsonlite (or another R json package)?
In R, reading a JSON file is quite a simple task. One can extract and read the data of a JSON file very efficiently using the fromJSON() function. The fromJSON() function takes the JSON file and returns the extracted data from the JSON file in the list format by default.
jsonlite: A Simple and Robust JSON Parser and Generator for R. A reasonably fast JSON parser and generator, optimized for statistical data and the web. Offers simple, flexible tools for working with JSON in R, and is particularly powerful for building pipelines and interacting with a web API.
JSON (JavaScript Object Notation, pronounced /ˈdʒeɪsən/; also /ˈdʒeɪˌsɒn/) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other serializable values).
The auto_unbox
argument does the trick with the jsonlite
package:
toJSON(list(op='abc'),auto_unbox=TRUE)
yields:
{"op":"abc"}
Update: based on comment, this approach is probably safer, and an example of why:
> jsonlite::toJSON(list(x=unbox(1),y=c(1,2)))
{"x":1,"y":[1,2]}
> jsonlite::toJSON(list(x=unbox(1),y=unbox(c(1,2)))) # expect error here.
Error: Tried to unbox a vector of length 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With