Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I encode an R vector of length 1 as a single value in json using the jsonlite R package?

Tags:

json

r

jsonlite

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)?

like image 339
seandavi Avatar asked Jul 10 '16 02:07

seandavi


People also ask

What does R JSON () do?

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.

What is Jsonlite?

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.

What is JSON encoding?

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).


1 Answers

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
like image 124
seandavi Avatar answered Oct 21 '22 16:10

seandavi