如何使用jsonlite R包将长度为1的R向量编码为json中的单个值? [英] How can I encode an R vector of length 1 as a single value in json using the jsonlite R package?

查看:139
本文介绍了如何使用jsonlite R包将长度为1的R向量编码为json中的单个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jsonlite包和toJSON函数将R列表编码为json.我有一个简单的项目,例如:

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

我希望成为:

{
  "op" : "abc"
}

相反,我得到了:

{
  "op" : ["abc"]
}

我要向后者提供json扼流圈的API,并且需要前者.关于如何从jsonlite(或另一个R json包)中获取以前的行为的任何建议吗?

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

推荐答案

auto_unbox参数使用jsonlite软件包可以解决问题:

The auto_unbox argument does the trick with the jsonlite package:

toJSON(list(op='abc'),auto_unbox=TRUE)

产量:

{"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

这篇关于如何使用jsonlite R包将长度为1的R向量编码为json中的单个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆