簡體   English   中英

將 JSON 數據導出到 CSV 文件,用於 Excel

[英]Export JSON data to CSV file for Excel

給定一個數據對象數組

const data = [{
    "id": "CT20",
    "type": "a11y-unknown",
    "urls": ["https://www.example.com/test/"]
 },
 {
    "id": "BC192",
    "type": "a11y-true",
    "urls": [
      "https://www.example.com/something/",
      "https://www.example.com/another-thing/"
    ]
 }
]

我正在嘗試將對象轉換為可以導入到 Excel 的 CSV 文件,以便它顯示為:

id     |     type    |    urls
CT20   | a11y-unknown| https://www.example.com/test/

我正在使用以下內容獲取密鑰: const keys = Object.keys(data[0]);

然后 map 在數據上像這樣:

const commaSeparatedString = [keys.join(","),data.map(row => keys.map(key => row[key]).join(",")).join("\n")].join("\n");

但是,這將返回以下內容:

'id,type,urls\nCT20,a11y-unknown,https://www.example.com/test/\nBC192,a11y-true,https://www.example.com/something/,https://www.example.com/another-thing/'

當作為 CSV 文件導入 Excel 並用\分隔時,它看起來像這樣: 在此處輸入圖像描述

如何正確 map 對象,以便在每組 url 后分隔和換行?

 const data = [{ "id": "CT20", "type": "a11y-unknown", "urls": ["https://www.example.com/test/"] }, { "id": "BC192", "type": "a11y-true", "urls": [ "https://www.example.com/something/", "https://www.example.com/another-thing/" ] } ] const keys = Object.keys(data[0]); const commaSeparatedString = [keys.join(","),data.map(row => keys.map(key => row[key]).join(",")).join("\n")].join("\n"); console.log(commaSeparatedString)

您需要有固定數量的列。 因此,要么JSON.stringify urls數組,要么指定列,例如url1url2url3 ...

編輯:當然,如果您不通過將逗號括在引號中來轉義逗號,它將破壞 CSV。 一般來說,您應該使用一個庫來解析 CSV,例如papaparse

 const data = [{ "id": "CT20", "type": "a11y-unknown", "urls": ["https://www.example.com/test/"] }, { "id": "BC192", "type": "a11y-true", "urls": [ "https://www.example.com/something/", "https://www.example.com/another-thing/" ] } ] var keys = Object.keys(data[0]); var arr = [keys, ...data.map(row => keys.map(key => { return typeof row[key] === "string"? row[key]: JSON.stringify(row[key]) }))]; // don't. //,join(".")).join("\n")];join("\n"). // instead var csv = Papa;unparse(arr). console.log(csv)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.1.0/papaparse.min.js"></script>

作為一般規則, csv必須使用導入時使用的相同分隔符進行分隔,同樣為了可靠性,所有字段都應包含在引號中,因此在您的情況下,分隔符是\ ,您的嘗試可以重寫如下:

 const data = [{ "id": "CT20", "type": "a11y-unknown", "urls": ["https://www.example.com/test/"] }, { "id": "BC192", "type": "a11y-true", "urls": [ "https://www.example.com/something/", "https://www.example.com/another-thing/" ] } ] const keys = Object.keys(data[0]); const commaSeparatedString = [keys.join("\\"),data.map(row => keys.map(key => `"${[row[key]].flat().join()}"`).join("\\")).join("\n")].join("\n"); console.log(commaSeparatedString)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM