编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

七爪源码:如何在 JavaScript 中将 JSON 转换为 CSV

wxchong 2024-08-19 23:56:47 开源技术 19 ℃ 0 评论

下面是我们如何在 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/小程序/网站源码资源!

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表