如何将含嵌套数组的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);
代码说明
formatField函数:解决CSV格式兼容问题,当字段包含逗号、引号或换行符时,用双引号包裹字段,同时将字段内的双引号转义为两个双引号,避免破坏CSV结构。- 嵌套数组展开:
- 先将格式化后的表头加入结果数组
- 遍历每个主对象,再遍历其
ids数组 - 根据当前条目在
ids中的索引,决定是否显示url - 将格式化后的字段组合成行,加入结果数组
- 生成最终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
相关产品推荐
相关产品推荐

