You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从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)

代码说明

  1. 列名调整:如果需要完全匹配目标JSON的字段大小写,使用rename()修改列名(可根据实际需求跳过)。
  2. 构造records:通过pmap()遍历每一行,将行内字段打包成fields对应的列表,保证每个records元素是独立对象。
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:52:45