网站首页 > 技术文章 正文
下面是我们如何在 JavaScript 中轻松地将 JSON 转换为 CSV:
function jsonToCsv(items) {
const header = Object.keys(items[0]); const headerString = header.join(','); // handle null or undefined values here
const replacer = (key, value) => value ?? ''; const rowItems = items.map((row) =>
header
.map((fieldName) => JSON.stringify(row[fieldName], replacer))
.join(',')
); // join header and body, and break into separate lines
const csv = [headerString, ...rowItems].join('\r\n'); return csv;
}const obj = [
{ color: 'red', maxSpeed: 120, age: 2 },
{ color: 'blue', maxSpeed: 100, age: 3 },
{ color: 'green', maxSpeed: 130, age: 2 },
];const csv = jsonToCsv(obj);console.log(csv);
这将是 CSV 输出:
color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2
了解步骤
我们创建了一个可重用的 jsonToCsv() 函数来让我们将多个 JSON 字符串转换为 CSV。 它需要一个包含对象的数组。 每个对象将在 CSV 输出中占据一行。
我们在此函数中所做的第一件事是获取将用于 CSV 标头的所有键。 我们希望数组中的所有对象都具有相同的键,因此我们使用 Object.keys() 方法将键从第一个对象项中提取到数组中。
const obj = [
{ color: 'red', maxSpeed: 120, age: 2 },
{ color: 'blue', maxSpeed: 100, age: 3 },
{ color: 'green', maxSpeed: 130, age: 2 },
];// { color: 'red', maxSpeed: 120, age: 2 }
console.log(obj[0]);// [ 'color', 'maxSpeed', 'age' ]
console.log(Object.keys(obj[0]));
获取键后,我们调用数组的 join() 方法将所有元素连接成 CSV 标头字符串。
const header = ['color', 'maxSpeed', 'age'];const headerString = arr.join(',');console.log(headerString); // color,maxSpeed,age
接下来,我们创建一个函数,该函数将作为回调传递给 JSON.stringify() 函数的 replacer 参数。 此函数将处理 JSON 数组中对象的未定义或空属性值。
const obj = { prop1: 'Earth', prop2: undefined };// replace undefined property values with empty string ('')
const replacer = (key, value) => value ?? '';const str = JSON.stringify(obj, replacer);// {"prop1":"Earth","prop2":""}
console.log(str);
然后我们使用 Array map() 方法从每个对象中获取属性值。 map() 接受一个回调函数,该函数在每个数组元素上调用以返回一个转换。
此回调使用标头数组来获取每个对象的所有键。 再次调用 map(),它会遍历每个键,获取对象中该键的对应值,并使用 JSON.stringify() 将其转换为字符串。
这个对 map() 的内部调用最终会产生一个数组,该数组包含数组中当前对象的所有字符串化属性值。
const header = ['color', 'maxSpeed', 'age'];const row = { color: 'red', maxSpeed: 120, age: 2 };const replacer = (key, value) => value ?? '';const rowItem = header.map((fieldName) =>
JSON.stringify(row[fieldName], replacer)
);// array of stringified property values
console.log(rowItem); // [ '"red"', '120', '2' ]
将对象转换为属性值数组后,使用 join() 将数组转换为 CSV 行。
['"red"', '120', '2'].join(',') // -> "red",120,2
因此,这种转换发生在 JSON 数组中的每个对象上,以生成 CSV 行列表,存储在我们原始示例中的 rowItems 变量中。
为了生成最终的 CSV 输出,我们使用扩展语法 (...) 将 headerString 和 rowItems 组合到一个数组中。
const headerString = ['color', 'maxSpeed', 'age'];const rowItems = ['"red",120,2', '"blue",100,3', '"green",130,2'];[headerString, ...rowItems];
/*
Output ->
[
[ 'color', 'maxSpeed', 'age' ],
'"red",120,2',
'"blue",100,3',
'"green",130,2'
]
*/
然后我们在这个数组上调用 join() 并使用 '\r\n' 字符串作为分隔符,以创建一个带有 CSV 标题的字符串,并且每个 CSV 行位于单独的行中。
const headerString = ['color', 'maxSpeed', 'age'];const rowItems = ['"red",120,2', '"blue",100,3', '"green",130,2'];console.log([headerString, ...rowItems].join('\r\n'));
/*
color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2
*/
关注七爪网,获取更多APP/小程序/网站源码资源!
猜你喜欢
- 2024-10-19 Node-RED系列(六):Node-RED解析节点的使用
- 2024-10-19 越南指数行情数据API接口(越南指数股票最新行情)
- 2024-10-19 Pinot 架构分析(pod架构)
- 2024-10-19 大模型开发者实战揭秘:SFT指令微调数据构建的全方位指南
- 2024-10-19 27K star!这款开源可视利器帮你一眼看穿JSON
- 2024-10-19 linux-shell命令处理json数据(linux检查json格式)
- 2024-10-19 MongoDB常用特性一览(mongodb4.2新特性)
- 2024-10-19 轻量级的原生JavaScript的Excel插件——JExcel
- 2024-10-19 5万字长文!搞定Spark方方面面(五)
- 2024-10-19 越南指数清单列表数据API接口(越南指数清单列表数据api接口在哪)
- 最近发表
- 标签列表
-
- cmd/c (64)
- c++中::是什么意思 (83)
- 标签用于 (65)
- 主键只能有一个吗 (66)
- c#console.writeline不显示 (75)
- pythoncase语句 (81)
- es6includes (73)
- sqlset (64)
- windowsscripthost (67)
- apt-getinstall-y (86)
- node_modules怎么生成 (76)
- chromepost (65)
- c++int转char (75)
- static函数和普通函数 (76)
- el-date-picker开始日期早于结束日期 (70)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- & (66)
- java (73)
- js数组插入 (83)
- linux删除一个文件夹 (65)
- mac安装java (72)
- eacces (67)
- 查看mysql是否启动 (70)
- 无效的列索引 (74)