JS小知識之如何將CSV轉(zhuǎn)換為JSON字符串
前言
大家好,今天和大家聊一聊,在前端開發(fā)中,我們?nèi)绾螌?CSV 格式的內(nèi)容轉(zhuǎn)換成 JSON 字符串,這個(gè)需求在我們處理數(shù)據(jù)的業(yè)務(wù)需求中十分常見,你是如何處理的呢,如果你有更好的方法歡迎在評論區(qū)補(bǔ)充。
一、使用 csvtojson 第三方庫
您可以使用 csvtojson 庫在 JavaScript 中快速將 CSV 轉(zhuǎn)換為 JSON 字符串:
index.js
import csvToJson from 'csvtojson'; const csvFilePath = 'data.csv'; const json = await csvToJson().fromFile(csvFilePath); console.log(json);
data.csv 文件
例如這樣的 data.csv 文件,其內(nèi)容如下:
color,maxSpeed,age "red",120,2 "blue",100,3 "green",130,2
最終生成的 JSON 數(shù)組字符串內(nèi)容如下:
[
{ color: 'red', maxSpeed: '120', age: '2' },
{ color: 'blue', maxSpeed: '100', age: '3' },
{ color: 'green', maxSpeed: '130', age: '2' }
]安裝 csvtojson
在使用 csvtojson 之前,您需要將其安裝到我們的項(xiàng)目中。您可以使用 NPM 或 Yarn CLI 執(zhí)行此操作。
npm i csvtojson # Yarn yarn add csvtojson
安裝后,將其引入到你的項(xiàng)目中,如下所示:
import csvToJson from 'csvtojson';
// CommonJS
const csvToJson = require('csvtojson');通過 fromFile() 方法,導(dǎo)入CSV文件
我們調(diào)用 csvtojson 模塊的默認(rèn)導(dǎo)出函數(shù)來創(chuàng)建將轉(zhuǎn)換 CSV 的對象。這個(gè)對象有一堆方法,每個(gè)方法都以某種方式與 CSV 到 JSON 的轉(zhuǎn)換相關(guān),fromFile() 就是其中之一。
它接受要轉(zhuǎn)換的 CSV 文件的名稱,并返回一個(gè) Promise,因?yàn)檗D(zhuǎn)換是一個(gè)異步過程。Promise 將使用生成的 JSON 字符串進(jìn)行解析。
直接將 CSV 字符串轉(zhuǎn)換為 JSON,fromString()
要直接從 CSV 數(shù)據(jù)字符串而不是文件轉(zhuǎn)換,您可以使用轉(zhuǎn)換對象的異步 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 的轉(zhuǎn)換
csvtojson 的默認(rèn)導(dǎo)出函數(shù)接受一個(gè)對象,用于指定選項(xiàng),可以自定義轉(zhuǎn)換過程。
其中一個(gè)選項(xiàng)是 header,這是一個(gè)用于指定 CSV 數(shù)據(jù)中的標(biāo)題的數(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' }
]
另一個(gè)是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 屬性,一個(gè)使用正則表達(dá)式示忽略某些列的選項(xiàng)。
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 轉(zhuǎn)換為行數(shù)組
通過將輸出選項(xiàng)設(shè)置為“csv”,我們可以生成一個(gè)數(shù)組列表,其中每個(gè)數(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 轉(zhuǎn) JSON
我們也可以在不使用任何第三方庫的情況下將 CSV 轉(zhuǎn)換為 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"
}
]
您可以完善上面的代碼處理更為復(fù)雜的 CSV 數(shù)據(jù)。
結(jié)束
今天的分享就到這里,如何將 CSV 轉(zhuǎn)換為 JSON 字符串,你學(xué)會(huì)了嗎?
到此這篇關(guān)于JS小知識之如何將CSV轉(zhuǎn)換為JSON字符串的文章就介紹到這了,更多相關(guān)JS將CSV轉(zhuǎn)換JSON字符串內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
原文:
https://medium.com/javascript-in-plain-english/javascript-convert-csv-to-json-91dbbd4ae436作者 :Coding Beauty
非直接翻譯,有自行改編和添加部分。
相關(guān)文章
微信小程序返回上一頁刷新組件數(shù)據(jù)的示例代碼
這篇文章主要介紹了微信小程序返回上一頁刷新組件數(shù)據(jù)的相關(guān)資料,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2024-03-03
JavaScript實(shí)現(xiàn)圖片懶加載(Lazyload)
這篇文章主要介紹了JavaScript實(shí)現(xiàn)圖片懶加載(Lazyload)的相關(guān)資料,需要的朋友可以參考下2016-11-11
Javascript 正則表達(dá)式實(shí)現(xiàn)為數(shù)字添加千位分隔符
在項(xiàng)目中做貨幣轉(zhuǎn)換的時(shí)候經(jīng)常需要可以實(shí)現(xiàn)自動(dòng)格式化輸入的數(shù)字,自動(dòng)千位分隔符,在網(wǎng)上也看到一些其他網(wǎng)友的實(shí)現(xiàn)的代碼,感覺都不是太滿意,于是自己研究了下,分享給大家。2015-03-03
原生js實(shí)現(xiàn)簡單的Ripple按鈕實(shí)例代碼
本篇文章主要介紹了原生js實(shí)現(xiàn)簡單的Ripple按鈕實(shí)例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-03-03
基于JS實(shí)現(xiàn)回到頁面頂部的五種寫法(從實(shí)現(xiàn)到增強(qiáng))
這篇文章主要介紹了基于JS實(shí)現(xiàn)回到頁面頂部的五種寫法(從實(shí)現(xiàn)到增強(qiáng))的相關(guān)資料,本文介紹的非常詳細(xì),實(shí)用性也非常高,非常具有參考借鑒價(jià)值,需要的朋友可以參考下2016-09-09
js判斷價(jià)格,必須為數(shù)字且不能為負(fù)數(shù)的實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄猨s判斷價(jià)格,必須為數(shù)字且不能為負(fù)數(shù)的實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-10-10
TypeScript轉(zhuǎn)javaScript的方法示例
本文主要介紹了TypeScript轉(zhuǎn)javaScript的方法示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06

