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

心已入冬 提交于 2019-11-30 05:44:44

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/38288159/how-can-i-encode-an-r-vector-of-length-1-as-a-single-value-in-json-using-the-jso

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!