【单个文件的转化】
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!"); }); }) }); });