我想將 CSV 轉換為 JSON 正確的資料型別
csv 檔案第二行是資料型別。資料有 300 多個屬性示例資料:
| 姓名 | 數字機槍 | 生命值 | 人類 |
|---|---|---|---|
| 細繩 | 數字 | 數字 | 布林值 |
| 騎士 | 100 | 500 | 真的 |
| 射手 | 50 | 200 | 真的 |
| 狗 | - | - | - |
如果字串為空回傳 null
如果數字為空回傳 0
如果布林值空回傳 false
我的 node.js 代碼:
const fs = require('fs')
const papa = require("papaparse")
const results = [];
const options = { header: true, dynamicTyping: true };
fs.createReadStream("characters.csv")
.pipe(papa.parse(papa.NODE_STREAM_INPUT, options))
.on("data", (data) => {
results.push(data);
}).on("end", () => {
console.log(results)
})
我期待的輸出:
[
{
"Name": "knight",
"DMG": 100,
"HP": 500,
"Human": true,
},
{
"Name": "archer",
"DMG": 50,
"HP": 200,
"Human": true,
},
{
"Name": "dog",
"DMG": 0,
"HP": 0,
"Human": false,
},
]
uj5u.com熱心網友回復:
選項選項..
在這種方法中,我快取了 headerTypes 并制作了一個小的輔助函式來回傳預期的型別
定義變數 let i = 0, headerTypes = {};
用這個替換你的 on.data 代碼
.on("data", (data) => {
if(i > 0){
for(let prop in data){
if(data.hasOwnProperty(prop)){
const value = data[prop];
data[prop] = typecast(headerTypes[prop], value);
}
}
}else{
//save types from row 0
headerTypes = data;
}
i ;
})
添加這個輔助函式
function typecast(type = '', value){
switch(type){
case "number":
return value || 0; //unary for int or float
case "boolean":
return value === !0; //typecast to Boolean will let any filled string like '-' be true, do this instead.
case "string":
default:
return String(value);
}
}
uj5u.com熱心網友回復:
嘗試像這樣覆寫 on.data 事件中的屬性
let i = 0; //define this outside, its only to skip that first row with headers.
if(i > 0){ //skipping first row
data.DMG = parseInt(data.DMG) || 0; //an int or 0
data.HP = parseInt(data.HP) || 0; //an int or 0
data.Human = data.Human === !0; //!0 = not false, will match true string or bool
results.push(data);
}
i ;//iterate
const fs = require('fs')
const papa = require("papaparse")
const results = [];
const options = { header: true, dynamicTyping: true };
let i = 0;
fs.createReadStream("characters.csv")
.pipe(papa.parse(papa.NODE_STREAM_INPUT, options))
.on("data", (data) => {
//add this here
if(i > 0){
data.DMG = parseInt(data.DMG) || 0; //an int or 0
data.HP = parseInt(data.HP) || 0; //an int or 0
data.Human = data.Human === !0; //!0 = not false, will match true string or bool
results.push(data);
}
i ;
//end add this here
}).on("end", () => {
console.log(results)
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/534881.html
