• node:json与csv互转


    【单个文件的转化】
     
    1.安装json2csv模块将json转成csv
     
    jsonToCSV.js
    var fs = require('fs');
    const Json2csvParser = require('json2csv').Parser;
    const fields = ['car', 'price', 'color', 'for'];
    
    let myData = fs.readFileSync('./data.json');
      
    const json2csvParser = new Json2csvParser({ fields });
    
    const csv = json2csvParser.parse(JSON.parse(myData));
    
    fs.writeFile("./data.csv", csv, function(err) {
        if(err) {
            return console.log(err);
        }
        
        console.log("The file was saved!");
    });
    data.json
    [
        {
          "car": "Audi",
          "price": 40000,
          "color": "blue",
          "for": ""
        }, {
          "car": "BMW",
          "price": 35000,
          "color": "black",
          "for": ""
        }, {
          "car": "Porsche",
          "price": 60000,
          "color": "green",
          "for": ""
        }
      ]
      
     
    2.安装csvtojson模块将csv转成json
     
    csvToJson.js
    const csvFilePath = "./data.csv"
    const csv=require('csvtojson');
    var fs = require('fs');
    
    csv()
    .fromFile(csvFilePath)
    .then((jsonObj)=>{
        jsonObj = JSON.stringify(jsonObj)
        fs.writeFile("./file/newData.json",jsonObj,'utf-8', function(err) {
            if(err) {
                return console.log(err);
            }
          
            console.log("The file was saved!");
        });
    })

    csv截图

    优化:

    【目录下多个文件转化】

     文件目录截图
     
     
    jsonToCSV.js
    let fs = require('fs');
    const curDirPath = 'F:/json2CSV/00originJson';
    const Json2csvParser = require('json2csv').Parser;
    
    fs.readdir(curDirPath, (err, files) => {
        if(err) {
            return console.log(err);
        }
        
        files.forEach(file => {
            
            fs.readFile(curDirPath + `/${file}`, 'utf-8', (err, data) => {
                if(err) {
                    return console.log(err);
                }
    
                let keyArr = [];
    
                data = JSON.parse(data);
    
                for(let i in data) {
                    keyArr.push(Object.keys(data[i]));
                }
    
                let keyArrSort = keyArr.sort((a, b) => {
                    return b.length - a.length
                })
    
                let fields = keyArrSort[0];
      
                const json2csvParser = new Json2csvParser({ fields });
    
                const csv = json2csvParser.parse(data);
         
                let csvFileName = file.replace(/.{1}[a-z]{1,}$/, ".csv");
    
                fs.writeFile(`./01csvFile/${csvFileName}`, csv, function(err) {
                    if(err) {
                        return console.log(err);
                    }
                    
                    console.log("The file was saved!");
                });
    
            });
        });
    });
    csvToJson.js
    const curDirPath = 'F:/json2CSV/01csvFile';
    const csv=require('csvtojson');
    let fs = require('fs');
    
    fs.readdir(curDirPath, (err, files) => {
        if(err) {
            return console.log(err);
        }
        
        files.forEach(fileName => {
            csv()
            .fromFile(`${curDirPath}/${fileName}`)
            .then((jsonObj)=>{
    
                jsonObj = JSON.stringify(jsonObj);
    
                let jsonFileName = fileName.replace(/.{1}[a-z]{1,}$/, ".json");
    
                fs.writeFile(`./02newJsonFile/${jsonFileName}`, jsonObj, 'utf-8', function(err) {
                    if(err) {
                        return console.log(err);
                    }
                
                    console.log("The file was saved!");
                });
            })
        });
    });


  • 相关阅读:
    libuv 中文编程指南(一)序言
    一些鲜为人知却非常实用的数据结构
    libuv 中文编程指南(二)libuv 基础
    Zookeeper 的 Lua 绑定(二)
    高度怀疑
    不能没有你
    第一次看流星雨记
    调侃下蓝网队 我还是比较极端的 不要好 那就要坏吧
    摇滚校园
    守法公民
  • 原文地址:https://www.cnblogs.com/yhquan/p/10879836.html
Copyright © 2020-2023  润新知