r 相当于 python df.to_dict(orient="list")

问题描述 投票:0回答:1

嗨,我正在尝试将闪亮应用程序中的 R tibble 转换为 json。 我可以使用

jsonlite::toJSON()
来做到这一点 不幸的是,接收者要求以不同的顺序输出。 我尝试过将输入从长输入转换为宽输入,但结果都是错误的。

创建 json 的 python 代码使用

df.to_dict(orient="list")

所以我需要一个 r 等价物。

对 json 没有太多经验,而且有点着急,所以非常感谢您的帮助

python r json shiny
1个回答
0
投票
library(dplyr)
library(jsonlite)

#Sample tibbble
tibble <- data.frame(col1 = 1:3, col2 = letters[1:3], col3 = c("x", "y", "z"))

#You can change the order with this
# tibble_reordered <- tibble %>% select(desired_order)

#Convert tibble to list of named vectors
tibble_list <- as.list(tibble) #Use tibble_reordered if you reordered it
tibble_list <- lapply(tibble_list, as.vector)
names(tibble_list) <- names(tibble)  # Set column names as keys

#Convert list to JSON
json_output <- toJSON(tibble_list, auto = FALSE)

cat(json_output)
© www.soinside.com 2019 - 2024. All rights reserved.