.csv to .json

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
/**
* .csv => .json
*/

'use strict';

const path = require('path');
const fs = require('fs');
const iconv = require('iconv-lite');

const string2json = (inputData) => {
let outData = [];

const str = iconv.decode(inputData, 'gbk');
let rows = str.split('\r\n');
const titles = rows[0].split(',')

for (let i = 1; i < rows.length; i++) {
let obj = {};

titles.map((item, index) => {
obj[item] = rows[i].split(',')[index];
})

outData.push(obj);
}
return outData;
};

const csv2json = async () => {
try {
// Read file to string
const inputData = await fs.readFileSync('./data.csv', {encoding: 'binary'});

// String to json
const outData = string2json(inputData);

// Write to file
await fs.writeFileSync('./data.json', JSON.stringify(outData));

console.log('Success!');
} catch (e) {
console.log(e);
}
}

csv2json();