网站首页 > 博客文章 正文
下面是我们如何在 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-09-17 Kudra 介绍:可以从任何文档工具中提取代码数据
- 2024-09-17 Linux系统管理员必备的监控工具(linux监控工具nmon)
- 2024-09-17 简洁而优雅,Python Tablib实现将数据导出为Excel, Json等N种格式
- 2024-09-17 奋战一年,LangChain首个稳定版本发布,LangGraph把智能体构建为图
- 2024-09-17 推荐几个开发必备的JSON工具(推荐几个开发必备的json工具有哪些)
- 2024-09-17 浅谈在Linux中使用mongoexport工具导出数据
- 2024-09-17 常用的图像标注工具汇总(图像标注主要包括哪些项目)
- 2024-09-17 Python新工具:用三行代码提取PDF表格数据
- 2024-09-17 有备无患「GitHub 热点速览」(有备无患better safe than sorry)
- 2024-09-17 13个MacOS很赞的开源小工具-IT开发利器
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- powershellfor (55)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)