CSV转JSON

市面上有很多现在的网站,可以实现csv转为需要的格式,但因为项目的csv格式比较特殊,需要手动实现自定义。

主要通过三方的 csvtojson npm 包实现。记录过程,方便自定义更多格式。

话不多说,简单说下流程。

需求

多语言包为csv格式,需要将该格式转为json,便于i18n进行懒加载。

i18文件夹结构

1
2
3
4
5
--i18n
|--en_us
|--en_US.csv
|--de_de
|--de_DE.csv

csv的格式大致如下

1
2
3
4
5
6
7
// i18n/en_us/en_US.csv
hello,hello
welcome,welcome

// i18n/de_de/de_DE.csv
hello,Hallo
welcome,Willkommen

转化后的结构

1
2
3
4
5
// output/en_US.json
{
hello: hello,
welcome: welcome
}

实现

打开命令行,执行

  • mkdir demo
  • cd ./demo
  • npm init
  • npm install csvtojson
  • cd >index.js
  • mkdir output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// index.js
const csv = require("csvtojson");
var fs = require("fs");

function walkSync(currentDirPath, callback) {
var fs = require("fs"),
path = require("path");
fs.readdirSync(currentDirPath, { withFileTypes: true }).forEach(function (
dirent
) {
var filePath = path.join(currentDirPath, dirent.name);
if (dirent.isFile()) {
callback(filePath, dirent);
} else if (dirent.isDirectory()) {
walkSync(filePath, callback);
}
});
}
function getFileArr() {
const csvFileArr = [];
walkSync("./i18n", function (filePath) {
// if(filePath.test(/+\.csv$/)){
if (filePath.includes(".csv")) {
const file = `./${filePath}`.replace(/\\/g, "/");
csvFileArr.push(file);
}
});
return csvFileArr
}

function csvTojson(fileName) {
csv({
noheader: true,
output: "csv",
})
.fromFile(`${fileName}`)
.then((jsonArr) => {
let jsonObj = {};
for (let index = 0; index < jsonArr.length; index++) {
const item = jsonArr[index];
jsonObj[item[0]] = item[1];
}
jsonObj = JSON.stringify(jsonObj);
let outFile = fileName.match(/(\w+)\.csv$/)[1];
fs.writeFile(
`./output/${outFile}.json`,
jsonObj,
"utf-8",
function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
}
);
});
}


const fileArr = getFileArr();
fileArr.forEach((item) => {
csvTojson(item);
});
------本文结束 感谢阅读------