我如何将CSV转换为JSON与数据类型在python或node.js?



我想把CSV转换成JSON正确的数据类型

csv文件第二行为数据类型。数据有超过300个属性示例数据:

<表类> 名称 DMG 惠普 人类 tbody><<tr>字符串数量数量布尔骑士100500对阿切尔50200对狗---

选项选项…

在这种方法中,我缓存了headerTypes并编写了一个小的帮助函数来返回预期的类型

定义变量let i = 0, headerTypes = {};

替换你的on。的数据代码

.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);
}
}

尝试重写on中的属性。数据事件如下

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)
})

相关内容

  • 没有找到相关文章

最新更新