JS小知識之如何將CSV轉換為JSON字符串
前言
大家好,今天和大家聊一聊,在前端開發(fā)中,我們如何將 CSV 格式的內容轉換成 JSON 字符串,這個需求在我們處理數(shù)據(jù)的業(yè)務需求中十分常見,你是如何處理的呢,如果你有更好的方法歡迎在評論區(qū)補充。
一、使用 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 數(shù)組字符串內容如下:
[ { color: 'red', maxSpeed: '120', age: '2' }, { color: 'blue', maxSpeed: '100', age: '3' }, { color: 'green', maxSpeed: '130', age: '2' } ]
安裝 csvtojson
在使用 csvtojson 之前,您需要將其安裝到我們的項目中。您可以使用 NPM 或 Yarn CLI 執(zhí)行此操作。
npm i csvtojson # Yarn yarn add csvtojson
安裝后,將其引入到你的項目中,如下所示:
import csvToJson from 'csvtojson'; // CommonJS const csvToJson = require('csvtojson');
通過 fromFile() 方法,導入CSV文件
我們調用 csvtojson 模塊的默認導出函數(shù)來創(chuàng)建將轉換 CSV 的對象。這個對象有一堆方法,每個方法都以某種方式與 CSV 到 JSON 的轉換相關,fromFile() 就是其中之一。
它接受要轉換的 CSV 文件的名稱,并返回一個 Promise,因為轉換是一個異步過程。Promise 將使用生成的 JSON 字符串進行解析。
直接將 CSV 字符串轉換為 JSON,fromString()
要直接從 CSV 數(shù)據(jù)字符串而不是文件轉換,您可以使用轉換對象的異步 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 的默認導出函數(shù)接受一個對象,用于指定選項,可以自定義轉換過程。
其中一個選項是 header,這是一個用于指定 CSV 數(shù)據(jù)中的標題的數(shù)組,可以將其替換成更易讀的別名。
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 轉換為行數(shù)組
通過將輸出選項設置為“csv”,我們可以生成一個數(shù)組列表,其中每個數(shù)組代表一行,包含該行所有列的值。
如下所示:
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 數(shù)據(jù)。
結束
今天的分享就到這里,如何將 CSV 轉換為 JSON 字符串,你學會了嗎?
到此這篇關于JS小知識之如何將CSV轉換為JSON字符串的文章就介紹到這了,更多相關JS將CSV轉換JSON字符串內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
原文:
https://medium.com/javascript-in-plain-english/javascript-convert-csv-to-json-91dbbd4ae436作者 :Coding Beauty
非直接翻譯,有自行改編和添加部分。
相關文章
JavaScript實現(xiàn)ArrayBuffer到Base64的轉換
本文探討了在 JavaScript 中將 ArrayBuffer 轉換為 Base64 字符串時遇到的棧溢出問題,并提供了幾種實用的解決方案,我們將通過生動的比喻來解釋相關概念,比較不同方法的性能和兼容性,最終提供一個平衡而實用的方法,需要的朋友可以參考下2024-10-10Omi v1.0.2發(fā)布正式支持傳遞javascript表達式
這篇文章主要介紹了Omi v1.0.2發(fā)布正式支持傳遞javascript表達式,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-03-03JS面向對象編程基礎篇(一) 對象和構造函數(shù)實例詳解
這篇文章主要介紹了JS面向對象編程對象和構造函數(shù),結合實例形式詳細分析了JS面向對象編程對象和構造函數(shù)具體概念、原理、使用方法及操作注意事項,需要的朋友可以參考下2020-03-03BootStrap與validator 使用筆記(JAVA SpringMVC實現(xiàn))
這篇文章主要介紹了BootStrap與validator 使用筆記(JAVA SpringMVC實現(xiàn))的相關資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-09-09