服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - js教程 - JS小知识,如何将 CSV 转换为 JSON 字符串

JS小知识,如何将 CSV 转换为 JSON 字符串

2024-01-04 13:07前端达人 js教程

今天和大家聊一聊,在前端开发中,我们如何将 CSV 格式的内容转换成 JSON 字符串,这个需求在我们处理数据的业务需求中十分常见,你是如何处理的呢?

JS小知识,如何将 CSV 转换为 JSON 字符串

使用 csvtojson 第三方库

您可以使用 csvtojson 库在 JavaScript 中快速将 CSV 转换为 JSON 字符串:

index.js

import csvToJson from 'csvtojson';
const csvFilePath = 'data.csv';
const json = await csvToJson().fromFile(csvFilePath);
console.log(json);

data.csv 文件

例如这样的 data.csv 文件,其内容如下:

color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2

最终生成的 JSON 数组字符串内容如下:

[
  { color: 'red', maxSpeed: '120', age: '2' },
  { color: 'blue', maxSpeed: '100', age: '3' },
  { color: 'green', maxSpeed: '130', age: '2' }
]

安装 csvtojson

在使用 csvtojson 之前,您需要将其安装到我们的项目中。您可以使用 NPM 或 Yarn CLI 执行此操作。

npm i csvtojson

# Yarn
yarn add csvtojson

安装后,将其引入到你的项目中,如下所示:

import csvToJson from 'csvtojson';

// CommonJS
const csvToJson = require('csvtojson');

通过 fromFile() 方法,导入CSV文件

我们调用 csvtojson 模块的默认导出函数来创建将转换 CSV 的对象。这个对象有一堆方法,每个方法都以某种方式与 CSV 到 JSON 的转换相关,fromFile() 就是其中之一。

它接受要转换的 CSV 文件的名称,并返回一个 Promise,因为转换是一个异步过程。 Promise 将使用生成的 JSON 字符串进行解析。

直接将 CSV 字符串转换为 JSON,fromString()

要直接从 CSV 数据字符串而不是文件转换,您可以使用转换对象的异步 fromString() 方法代替:

index.js

import csvToJson from 'csvtojson';
const csv = `"First Name","Last Name","Age"
"Russell","Castillo",23
"Christy","Harper",35
"Eleanor","Mark",26`;
const json = await csvToJson().fromString(csv);
console.log(json);
输出:
[
  { 'First Name': 'Russell', 'Last Name': 'Castillo', Age: '23' },
  { 'First Name': 'Christy', 'Last Name': 'Harper', Age: '35' },
  { 'First Name': 'Eleanor', 'Last Name': 'Mark', Age: '26' }
]

自定义 CSV 到 JSON 的转换

csvtojson 的默认导出函数接受一个对象,用于指定选项,可以自定义转换过程。

其中一个选项是 header,这是一个用于指定 CSV 数据中的标题的数组,可以将其替换成更易读的别名。

index.js

import csvToJson from 'csvtojson';
const csv = `"First Name","Last Name","Age"
"Russell","Castillo",23
"Christy","Harper",35
"Eleanor","Mark",26`;
const json = await csvToJson({
  headers: ['firstName', 'lastName', 'age'],
}).fromString(csv);
console.log(json);
输出 :
[
  { firstName: 'Russell', lastName: 'Castillo', age: '23' },
  { firstName: 'Christy', lastName: 'Harper', age: '35' },
  { firstName: 'Eleanor', lastName: 'Mark', age: '26' }
]

另一个是delimeter,用来表示分隔列的字符:

import csvToJson from 'csvtojson';

const csv = `"First Name"|"Last Name"|"Age"
"Russell"|"Castillo"|23
"Christy"|"Harper"|35
"Eleanor"|"Mark"|26`;
const json = await csvToJson({
  headers: ['firstName', 'lastName', 'age'],
  delimiter: '|',
}).fromString(csv);

输出:

[
  { firstName: 'Russell', lastName: 'Castillo', age: '23' },
  { firstName: 'Christy', lastName: 'Harper', age: '35' },
  { firstName: 'Eleanor', lastName: 'Mark', age: '26' }
]

我们还可以使用 ignoreColumns 属性,一个使用正则表达式示忽略某些列的选项。

import csvToJson from 'csvtojson';

const csv = `"First Name"|"Last Name"|"Age"
"Russell"|"Castillo"|23
"Christy"|"Harper"|35
"Eleanor"|"Mark"|26`;
const json = await csvToJson({
  headers: ['firstName', 'lastName', 'age'],
  delimiter: '|',
  ignoreColumns: /lastName/,
}).fromString(csv);
console.log(json);

将 CSV 转换为行数组

通过将输出选项设置为“csv”,我们可以生成一个数组列表,其中每个数组代表一行,包含该行所有列的值。

如下所示:

index.js

import csvToJson from 'csvtojson';

const csv = `color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2`;
const json = await csvToJson({
  output: 'csv',
}).fromString(csv);
console.log(json);
输出:
[
  [ 'red', '120', '2' ],
  [ 'blue', '100', '3' ],
  [ 'green', '130', '2' ]
]

使用原生的JS处理 CSV 转 JSON

我们也可以在不使用任何第三方库的情况下将 CSV 转换为 JSON。

index.js

function csvToJson(csv) {
  // \n or \r\n depending on the EOL sequence
  const lines = csv.split('\n');
  const delimeter = ',';

  const result = [];
  const headers = lines[0].split(delimeter);
  for (const line of lines) {
    const obj = {};
    const row = line.split(delimeter);
    for (let i = 0; i < headers.length; i++) {
      const header = headers[i];
      obj[header] = row[i];
    }
    result.push(obj);
  }
  // Prettify output
  return JSON.stringify(result, null, 2);
}

const csv = `color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2`;
const json = csvToJson(csv);
console.log(json);

输出:

[
  {
    "color": "color",
    "maxSpeed": "maxSpeed",
    "age": "age"
  },
  {
    "color": "\"red\"",
    "maxSpeed": "120",
    "age": "2"
  },
  {
    "color": "\"blue\"",
    "maxSpeed": "100",
    "age": "3"
  },
  {
    "color": "\"green\"",
    "maxSpeed": "130",
    "age": "2"
  }
]

您可以完善上面的代码处理更为复杂的 CSV 数据。

在线csv转json

在线csv转json工具

结束

今天的分享就到这里,如何将 CSV 转换为 JSON 字符串,你学会了吗?

原文地址:https://www.toutiao.com/article/7193889075424920101/

延伸 · 阅读

精彩推荐