在 JavaScript 中將 CSV 轉換為 JSON

Shraddha Paghdar 2022年5月1日
在 JavaScript 中將 CSV 轉換為 JSON

CSV 是一個逗號分隔值檔案,副檔名為 .csv,允許以表格格式儲存資料。今天的文章將介紹如何在不使用第三方 npm 包的情況下將資料從 CSV 檔案轉換為 JavaScript Object Notation (JSON)。

與普通轉換的主要區別在於逗號可以分隔每一行的值,而我們知道,不同的列也是用逗號分隔的。

在 JavaScript 中將 CSV 轉換為 JSON

在這種方法中,我們將 CSV 檔案的內容放入一個陣列中,並根據分隔符拆分陣列的內容。CSV 檔案中的所有行都轉換為 JSON 物件,這些物件新增到結果陣列中,然後將其轉換為 JSON,並生成相應的 JSON 輸出檔案。

  1. 使用預設的 fs npm 包讀取 CSV 檔案。 (這是一個可選步驟,你可以直接提供陣列格式的資料)
  2. 將資料轉換成字串,拆分成陣列。
  3. 建立一個單獨的標題陣列。
  4. 對於每個剩餘的資料行,執行以下操作:
    4.1. 建立一個空物件來儲存當前行的結果值。
    4.2. 將字串 currentArrayString 宣告為當前陣列值以更改分隔符並將生成的字串儲存在新字串 string 中。
    4.3. 如果遇到雙引號 ("),我們保留逗號;否則,我們用管道| 替換它們。
    4.4. 繼續將我們迴圈的字元新增到字串中。
    4.5.使用 | 分割字串並將值儲存在屬性陣列中。
    4.6.如果每個頭的值包含多個用逗號分隔的資料,我們將其儲存為陣列;否則,直接儲存該值。
    4.7.將生成的物件新增到我們的結果陣列中。
  5. 將結果陣列轉換為 JSON,列印資料,或將其儲存在 JSON 檔案中。

下面的程式碼展示了上面提到的在 JavaScript 中的實現。

const fs = require("fs");
csv = fs.readFileSync("username.csv")

const array = csv.toString().split("\n");

/* Store the converted result into an array */
const csvToJsonResult = [];

/* Store the CSV column headers into seprate variable */
const headers = array[0].split(", ")

/* Iterate over the remaning data rows */
for (let i = 1; i < array.length - 1; i++) {
/* Empty object to store result in key value pair */
const jsonObject = {}
/* Store the current array element */
const currentArrayString = array[i]
let string = ''

let quoteFlag = 0
for (let character of currentArrayString) {
	if (character === '"' && quoteFlag === 0) {
	    quoteFlag = 1
	}
	else if (character === '"' && quoteFlag == 1) quoteFlag = 0
	if (character === ', ' && quoteFlag === 0) character = '|'
	if (character !== '"') string += character
}

let jsonProperties = string.split("|")

for (let j in headers) {
	if (jsonProperties[j].includes(", ")) {
	jsonObject[headers[j]] = jsonProperties[j]
		.split(", ").map(item => item.trim())
	}
	else jsonObject[headers[j]] = jsonProperties[j]
}
/* Push the genearted JSON object to resultant array */
csvToJsonResult.push(jsonObject)
}
/* Convert the final array to JSON */
const json = JSON.stringify(csvToJsonResult);
console.log(json)

上述程式碼的輸出將根據提供的輸入資料而有所不同。

輸出:

[
  {
    "name": "John",
    "quote": "Hello World"
  },
  {
    "name": "Alma",
    "quote": "Have a nice day"
  }
]

此處演示

Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn

相關文章 - JavaScript CSV

相關文章 - JavaScript JSON