-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflatten-json.js
96 lines (86 loc) · 2.09 KB
/
flatten-json.js
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
Reads all the JSON files in records.json
flattens each one to key-value pairs
writes them as an array to alldata.json
generates a CVS file to alldata.csv
example
// records-json/jim.json
{
info: {
name: "Jim", age: 27, hobby: "tennis"
}
}
// records-json/jane.json
{
info: {
name: "Jane", age: 28, location: "Tokyo"
}
}
// alldata.json
[
{ name: "Jim", age: 27, hobby: "tennis" },
{ name: "Jane", age: 28, location: "Tokyo" }
]
// alldata.csv
"name","age","hobby","location"
"Jim",27,"tennis",
"Jane",28,,"Tokyo"
*/
import fs from 'fs';
import fsP from 'fs/promises';
const filenames = fs.readdirSync('records-json').filter(f => f.endsWith('.json'));
const datas = [];
for (const name of filenames) {
const jsonFilename = `records-json/${name}`;
const data = JSON.parse(fs.readFileSync(jsonFilename, {encoding: 'utf-8'}));
data.report = { reportId: jsonFilename };
datas.push(data);
}
const flatDatas = [];
const names = new Set();
for (const data of datas) {
const flat = {};
flatDatas.push(flat);
for (const [group, entries] of Object.entries(data)) {
if (Array.isArray(entries)) {
entries.forEach(e => {
names.add(e);
flat[e] = true;
});
} else {
for (const [key, value] of Object.entries(entries)) {
if (typeof value === 'object') {
//
} else {
names.add(key);
flat[key] = value;
}
}
}
}
}
fs.writeFileSync('alldata.json', JSON.stringify(flatDatas));
function writeRow(f, row) {
const cells = [];
for (const v of row) {
if (v === undefined) {
cells.push('');
} else if (typeof v === 'string') {
cells.push(`"${v.replaceAll('"', '""')}"`);
} else {
cells.push(v.toString());
}
}
f.write(`${cells.join(',')}\r\n`);
}
const f = await fsP.open('alldata.csv', 'w');
f.write(new Uint8Array([0xEF, 0xBB, 0xBF])); // write BOM
writeRow(f, names.values());
for (const data of flatDatas) {
const row = [];
for (const name of names.values()) {
row.push(data[name]);
}
writeRow(f, row);
}
f.close();