在R中编写JSON标量。

huangapple go评论68阅读模式
英文:

Write json scalars in R

问题

在 [tag:R] 中,我有一个数据框中的一些数据,需要将其导出为 jsonl 格式。在 jsonl 中,每一行都是有效的 JSON。正如相关问题所示,您可以通过将 jsonlite::toJSON() 应用于每一行来轻松实现这一点。我的问题是,我需要其中一个变量为标量字符串,但 toJSON 将任何 R 向量转换为列表:

library(tidyverse)
library(jsonlite)
d <- tibble(
  id = 1:3,
  text = c("this is a string", "this is another string", "yet another string")
) 

jl <- d |>
  transpose() |>
  map_chr(toJSON) 

jl

我需要 text 为标量。期望的输出如下:

#&gt; [1] "{\"id\":[1],\"text\":\"this is a string\"}"      
#&gt; [2] "{\"id\":[2],\"text\":\"this is another string\"}"
#&gt; [3] "{\"id\":[3],\"text\":\"yet another string\"}"
英文:

In [tag:R], I have some data in a data frame and need to export it to jsonl. In jsonl each line is its own valid json. As the linked question shows, you can easily do that by applying jsonlite::toJSON() to each row. My problem is that I need one of the variables to be a scalar string, but toJSON makes any vector R vector into a list:

library(tidyverse)
library(jsonlite)
#&gt; 
#&gt; Attaching package: &#39;jsonlite&#39;
#&gt; The following object is masked from &#39;package:purrr&#39;:
#&gt; 
#&gt;     flatten
d &lt;- tibble(
  id = 1:3,
  text = c(&quot;this is a string&quot;, &quot;this is another string&quot;, &quot;yet another string&quot;)
) 

jl &lt;- d |&gt; 
  transpose() |&gt; 
  map_chr(toJSON) 

jl
#&gt; [1] &quot;{\&quot;id\&quot;:[1],\&quot;text\&quot;:[\&quot;this is a string\&quot;]}&quot;      
#&gt; [2] &quot;{\&quot;id\&quot;:[2],\&quot;text\&quot;:[\&quot;this is another string\&quot;]}&quot;
#&gt; [3] &quot;{\&quot;id\&quot;:[3],\&quot;text\&quot;:[\&quot;yet another string\&quot;]}&quot;

I need text to be scalar. Desired output:

#&gt; [1] &quot;{\&quot;id\&quot;:[1],\&quot;text\&quot;:\&quot;this is a string\&quot;}&quot;      
#&gt; [2] &quot;{\&quot;id\&quot;:[2],\&quot;text\&quot;:\&quot;this is another string\&quot;}&quot;
#&gt; [3] &quot;{\&quot;id\&quot;:[3],\&quot;text\&quot;:\&quot;yet another string\&quot;}&quot;

答案1

得分: 3

We may use auto_unbox = TRUE

library(purrr)
library(jsonlite)
d |&gt; 
  transpose() |&gt; 
  map_chr(toJSON, auto_unbox = TRUE)

-output

[1] "{\"id\":1,\"text\":\"this is a string\"}"
[2] "{\"id\":2,\"text\":\"this is another string\"}"
[3] "{\"id\":3,\"text\":\"yet another string\"}"
英文:

We may use auto_unbox = TRUE

library(purrr)
library(jsonlite)
d |&gt; 
  transpose() |&gt; 
  map_chr(toJSON, auto_unbox = TRUE)

-output

[1] &quot;{\&quot;id\&quot;:1,\&quot;text\&quot;:\&quot;this is a string\&quot;}&quot; 
[2] &quot;{\&quot;id\&quot;:2,\&quot;text\&quot;:\&quot;this is another string\&quot;}&quot;
[3] &quot;{\&quot;id\&quot;:3,\&quot;text\&quot;:\&quot;yet another string\&quot;}&quot;    

huangapple
  • 本文由 发表于 2023年3月4日 01:01:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629931.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定