从tibble转换为JSON时遇到格式不符问题
解决Tibble转指定JSON格式的问题
你当前的代码生成的JSON中,fields是包含所有行的数组,而目标格式要求每个records元素对应一个独立的fields对象,同时需要额外添加顶层的fieldKey字段。问题根源在于rowwise() + nest()的嵌套方式导致结构不符合预期,且未补充所需的顶层字段。
修正代码
直接将每一行数据转换为含fields的独立列表,再组合成目标结构,同时添加fieldKey:
library(tibble) library(jsonlite) library(dplyr) library(purrr) # 原始数据框 original_tibble <- tibble::tibble( matter = c("「Organization Module - Organization of the address book panel", "「Member」 module - set the department"), `Problem description` = c("It is essentially the same as the above requirements", "After selecting a person, you can adjust multiple departments to which he belongs\nAfter selecting a department, you can also add members to the current department"), classification = c("Product demand", "product demand"), `review date` = c("2019-10-30T00:00:00.000Z", "2019-10-29T16:00:00.000Z") ) # 可选:调整列名以匹配目标JSON的字段大小写 original_tibble <- original_tibble %>% rename( "problem description" = `Problem description`, "Review date" = `review date` ) # 构造records列表:每一行对应一个带fields的对象 records <- original_tibble %>% pmap(function(...) { list(fields = list(...)) }) # 转换为JSON,auto_unbox确保单个对象不被转为数组 result_json <- toJSON( list(records = records, fieldKey = "name"), pretty = TRUE, auto_unbox = TRUE ) # 输出结果 cat(result_json)
代码说明
- 列名调整:如果需要完全匹配目标JSON的字段大小写,使用
rename()修改列名(可根据实际需求跳过)。 - 构造records:通过
pmap()遍历每一行,将行内字段打包成fields对应的列表,保证每个records元素是独立对象。 - JSON转换:添加顶层
fieldKey字段,auto_unbox = TRUE避免将单个fields对象转为数组,确保结构符合要求。
输出结果
运行后将生成你需要的JSON格式:
{ "records": [ { "fields": { "matter": "「Organization Module - Organization of the address book panel", "problem description": "It is essentially the same as the above requirements", "classification": "Product demand", "Review date": "2019-10-30T00:00:00.000Z" } }, { "fields": { "matter": "「Member」 module - set the department", "problem description": "After selecting a person, you can adjust multiple departments to which he belongs\nAfter selecting a department, you can also add members to the current department", "classification": "product demand", "Review date": "2019-10-29T16:00:00.000Z" } } ], "fieldKey": "name" }
内容的提问来源于stack exchange,提问作者Netmarketr
相关产品推荐
相关产品推荐

