我想转换以下数据:

CERTIFICADO = tibble::tibble(type = "cuar_private_file",
                             title = "Certificado Participacion CC FECHIC 2023 30207",
                             excerpt = "Certificado Participacion CC FECHIC 2023 30207",
                             post_date = "2024-01-21 21:00:00",
                             owners = 1965,
                             attachments = "Certificado_Participacion_CC_FECHIC_2023_30207.pdf",
                             method = "copy")

转换为以下格式的JSON文件:

[
  {
    "type": "cuar_private_file",
    "title": "Certificado Participacion CC FECHIC 2023 30207",
    "excerpt": "Certificado de Participacion de Folio 30207 Cohorte FECHIC año 2023",
    "post_date": "2024-01-21 21:00:00",
    "owners": 
    { "usr": [1965]
    },
    "attachments":
    { "Certificado_Participacion_CC_FECHIC_2023_30207.pdf":
    { "method": "copy"
    }}
  }
]

我正在使用以下代码:

cat(toJSON(CERTIFICADO, pretty=TRUE), file = 'CERTIFICADO3.json')

但是这段代码给了我以下JSON文件:

[
  {
    "type": "cuar_private_file",
    "title": "Certificado Participacion CC FECHIC 2023 30207",
    "excerpt": "Certificado Participacion CC FECHIC 2023 30207",
    "post_date": "2024-01-21 21:00:00",
    "owners": 1965,
    "attachments": "Certificado_Participacion_CC_FECHIC_2023_30207.pdf",
    "method": "copy"
  }
]

为了获得我想要的JSON文件,我可以对代码进行什么调整?或者有其他方法可以做到这一点?

提前谢谢!

推荐答案

你可以对数据进行调整.框一点就可以得到你想要的形状

library(dplyr)
library(purrr)
library(jsonlite)
CERTIFICADO %>% 
  mutate(owners = map(owners, ~list(usr=.x)),
         attachments = map2(attachments, method, ~setNames(list(list(method=unbox(.y))), .x)),
         method=NULL) %>% 
  jsonlite::toJSON(pretty=TRUE)

它会返回

[
  {
    "type": "cuar_private_file",
    "title": "Certificado Participacion CC FECHIC 2023 30207",
    "excerpt": "Certificado Participacion CC FECHIC 2023 30207",
    "post_date": "2024-01-21 21:00:00",
    "owners": {
      "usr": [1965]
    },
    "attachments": {
      "Certificado_Participacion_CC_FECHIC_2023_30207.pdf": {
        "method": "copy"
      }
    }
  }
]

秘诀是添加一些额外的 list 来获得你想要的形状.

R相关问答推荐

是否有任何解决方案可以优化VSCode中RScript的图形绘制?

根据收件箱中的特定值提取列名

在R中列表的结尾添加数字载体

向gggplot 2中的数据和轴标签添加大写和星号

derrr summarise每个组返回多行?

ggplot2中的X轴显示数值,单位为百,而不是十

修改用R编写的用户定义函数

使用tidy—select创建一个新的带有mutate的摘要变量

当我们有多个特殊字符时,使用gsub删除名称和代码'

可以替代与NSE一起使用的‘any_of()’吗?

您是否可以折叠R中的重复行,同时保留基于所选列的值?

SHINY:使用JS函数应用的CSS样式显示HTML表格

汇总数据帧中的复制列,保持行的唯一性

使用geom_iles在一个切片中包含多个值

位置_道奇在geom_point图中不躲避

按两个条件自动过滤数据

具有由向量定义的可变步长的序列

R,将组ID分配给另一个观测ID变量中的值的组合

通过不完全重叠的多个柱连接

当y为负值时,无法使stat_cor正确定位到底部?