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

如何将含嵌套数组的JSON转换为指定格式的CSV?

问题:将含嵌套数组的JSON转换为指定格式的CSV

需要把包含嵌套数组的JSON对象数组转换为CSV,目标格式要求:

  • 列头为url、id、type
  • 同一url对应的多个id/type条目,仅首行显示完整url,其余行url列留空

原始JSON数据

[
  {
    "url": "https://www.example.com/something",
    "ids": [
      { "id": "F22", "type": "a11y-true" },
      { "id": "C30", "type": "a11y-unknown" }
    ]
  },
  {
    "url": "https://www.example.com/something-else",
    "ids": [
      { "id": "F23", "type": "a11y-true" },
      { "id": "U10", "type": "a11y-unknown" },
      { "id": "CR14", "type": "a11y-unknown" },
      { "id": "RH03", "type": "a11y-true" }
    ]
  }
]

尝试的代码(未处理嵌套数组)

const items = data
const header = Object.keys(items[0])
const csv = [header.join(','),...items.map(row => header.map(fieldName => JSON.stringify(row[fieldName])).join(','))].join('\r\n')
console.log(csv)

当前错误输出

"https://www.example.com/something",[{"id":"F22","type":"a11y-true"},{"id":"C30","type":"a11y-unknown"}]
"https://www.example.com/something-else",[{"id":"F23","type":"a11y-true"},{"id":"U10","type":"a11y-unknown"},{"id":"CR14","type":"a11y-unknown"},{"id":"RH03","type":"a11y-true"}]

解决方案

核心思路是展开嵌套的ids数组,为每个嵌套对象生成单独一行,并控制url列的显示逻辑:

完整代码

// 处理字段格式,兼容CSV规则:含特殊字符的字段用双引号包裹,内部双引号转义
const formatField = (field) => {
  const str = String(field);
  return /[,"\n]/.test(str)? `"${str.replace(/"/g, '""')}"` : str;
};

const data = [/* 放入你的原始JSON数据 */];
const header = ['url', 'id', 'type'];
const rows = [header.map(formatField).join(',')];

data.forEach(item => {
  item.ids.forEach((idObj, index) => {
    // 仅当前url的首行显示完整url,其余行留空
    const url = index === 0? item.url : '';
    const row = [url, idObj.id, idObj.type].map(formatField);
    rows.push(row.join(','));
  });
});

const csv = rows.join('\r\n');
console.log(csv);

代码说明

  1. formatField函数:解决CSV格式兼容问题,当字段包含逗号、引号或换行符时,用双引号包裹字段,同时将字段内的双引号转义为两个双引号,避免破坏CSV结构。
  2. 嵌套数组展开:
    • 先将格式化后的表头加入结果数组
    • 遍历每个主对象,再遍历其ids数组
    • 根据当前条目在ids中的索引,决定是否显示url
    • 将格式化后的字段组合成行,加入结果数组
  3. 生成最终CSV:将所有行用换行符连接,得到符合要求的CSV内容。

最终输出

url,id,type
https://www.example.com/something,F22,a11y-true
,C30,a11y-unknown
https://www.example.com/something-else,F23,a11y-true
,U10,a11y-unknown
,CR14,a11y-unknown
,RH03,a11y-true

内容的提问来源于stack exchange,提问作者Matt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:15:06