我如何将CSV转换为Python或node.js中的JSON数据类型?

2wnc66cl  于 2022-11-19  发布在  Python
关注(0)|答案(2)|浏览(139)

我要将CSV转换为JSON正确数据类型
csv文件第二行是数据类型。数据有300多个属性示例数据:
| 名称名称名称|DMG公司|惠普|人类|
| - -|- -|- -|- -|
| 串|号码|号码|布尔的|
| 骑士|100个|五百个|真的|
| 弓箭手|五十个|二百|真的|
| 挡块|- -|- -|- -|
如果字符串为空,则返回null
如果number为空,则返回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)
    })

输出I预期:

[
    {
        "Name": "knight",
        "DMG": 100,
        "HP": 500,
        "Human": true,
    },
    {
        "Name": "archer",
        "DMG": 50,
        "HP": 200,
        "Human": true,
    },
    {
        "Name": "dog",
        "DMG": 0,
        "HP": 0,
        "Human": false,
    },
]
jmp7cifd

jmp7cifd1#

选项选项..

在这种方法中,我缓存了headerTypes并创建了一个小的helper函数来返回所需的类型

定义变量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);
    }
}
jw5wzhpr

jw5wzhpr2#

尝试覆盖www.example.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)
})

相关问题