如何调整R代码将指定tibble转换为目标格式的JSON文件
如何将指定tibble转换为目标JSON格式?
原Tibble数据
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')
解决方案
需要先调整tibble的嵌套结构,使其匹配目标JSON的层级,再执行转换:
library(tibble) library(jsonlite) # 调整数据结构以匹配目标JSON CERTIFICADO_ADJUSTED = tibble( 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 = list(usr = list(1965)), attachments = list( setNames(list(method = "copy"), "Certificado_Participacion_CC_FECHIC_2023_30207.pdf") ) ) # 生成目标格式的JSON文件 cat(toJSON(CERTIFICADO_ADJUSTED, pretty = TRUE, auto_unbox = FALSE), file = 'CERTIFICADO3.json')
关键调整说明
- excerpt字段:直接替换为目标文本内容
- owners字段:将单个数值包装为嵌套列表,生成
{"usr": [1965]}的结构 - attachments字段:用
setNames()将方法对象绑定到文件名作为键,生成多层嵌套结构 - JSON转换参数:
auto_unbox = FALSE确保嵌套列表保留数组和对象的层级,不会被自动拆箱
内容的提问来源于stack exchange,提问作者Rousitutu
相关产品推荐
相关产品推荐

