嵌套JSON转CSV展平异常求助:JavaScript代码问题排查
解决嵌套JSON展平转CSV丢失字段的问题
嘿,我之前也踩过JSON展平转CSV的坑!你说的customer.addresses只保留了addresstype:r,其他字段直接跳过,大概率是你的展平逻辑没处理好嵌套对象/数组的遍历——要么是没递归遍历所有属性,要么是处理数组的时候只取了某个字段就终止了,导致其他属性直接丢失,转成CSV后Excel自然没法正常显示。
我给你一套经过验证的JavaScript方案,应该能解决你的问题:
第一步:正确的JSON展平函数
这个函数会递归遍历所有嵌套对象和数组,把所有层级的属性都展平成带路径的键名(比如customer.addresses[0].city),不会丢失任何字段:
function flattenJSON(obj, parentKey = '', sep = '.') { let result = {}; for (const key in obj) { if (obj.hasOwnProperty(key)) { const newKey = parentKey ? `${parentKey}${sep}${key}` : key; // 处理嵌套对象 if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) { Object.assign(result, flattenJSON(obj[key], newKey, sep)); } // 处理数组(给每个元素加索引,避免字段覆盖) else if (Array.isArray(obj[key])) { obj[key].forEach((item, index) => { if (typeof item === 'object' && item !== null) { Object.assign(result, flattenJSON(item, `${newKey}[${index}]`, sep)); } else { result[`${newKey}[${index}]`] = item; } }); } // 普通字段直接赋值 else { result[newKey] = obj[key]; } } } return result; }
第二步:安全转CSV的函数
转CSV的时候要处理特殊字符(比如逗号、引号、换行),不然Excel打开会乱序或者拆分错误:
function jsonToCSV(flattenedData) { // 提取所有表头字段 const headers = Object.keys(flattenedData[0]); // 给表头加引号(避免特殊字符干扰) const csvHeaders = headers.map(header => `"${header.replace(/"/g, '""')}"`).join(','); // 处理每一行数据 const csvRows = flattenedData.map(row => { return headers.map(fieldName => { let value = row[fieldName] || ''; // 如果字段包含特殊字符,加引号并转义内部的引号 if (typeof value === 'string' && (value.includes(',') || value.includes('"') || value.includes('\n'))) { value = `"${value.replace(/"/g, '""')}"`; } return value; }).join(','); }); // 拼接表头和行数据 return [csvHeaders, ...csvRows].join('\n'); }
第三步:使用示例
假设你的原始JSON数据是类似这样的结构(模拟你提到的内容):
const rawCustomerData = [ { customer: { addresses: [ { addresstype: 'r', city: 'New York', countrycode: 'US', countycode: 'NY' } ], companyName: 'Acme Corp' } } ];
调用函数处理:
// 展平每个JSON对象 const flattenedData = rawCustomerData.map(item => flattenJSON(item)); // 转成CSV格式 const csvOutput = jsonToCSV(flattenedData); // 可以打印或者导出到文件 console.log(csvOutput);
这样处理后,展平后的字段会包含customer.addresses[0].addresstype、customer.addresses[0].city、customer.addresses[0].countrycode等所有属性,转成CSV后用Excel打开就能正常显示所有字段了。
如果你的addresses是单个对象而不是数组,这个函数也能正常处理,会生成customer.addresses.city这样的键名,不会丢失数据。
内容的提问来源于stack exchange,提问作者David Brierton
相关产品推荐
相关产品推荐

