英文:
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
为标量。期望的输出如下:
#> [1] "{\"id\":[1],\"text\":\"this is a string\"}"
#> [2] "{\"id\":[2],\"text\":\"this is another string\"}"
#> [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)
#>
#> Attaching package: 'jsonlite'
#> The following object is masked from 'package:purrr':
#>
#> flatten
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
#> [1] "{\"id\":[1],\"text\":[\"this is a string\"]}"
#> [2] "{\"id\":[2],\"text\":[\"this is another string\"]}"
#> [3] "{\"id\":[3],\"text\":[\"yet another string\"]}"
I need text
to be scalar. Desired output:
#> [1] "{\"id\":[1],\"text\":\"this is a string\"}"
#> [2] "{\"id\":[2],\"text\":\"this is another string\"}"
#> [3] "{\"id\":[3],\"text\":\"yet another string\"}"
答案1
得分: 3
We may use auto_unbox = TRUE
library(purrr)
library(jsonlite)
d |>
transpose() |>
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 |>
transpose() |>
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\"}"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论