-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransformJsonFilesToInsertSQL.js
43 lines (36 loc) · 1.31 KB
/
transformJsonFilesToInsertSQL.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
const fs = require('fs');
const path = require('path');
const jsonFilesDir = './USA';
const tableName = 'County';
fs.readdir(jsonFilesDir, (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
files.forEach(file => {
const filePath = path.join(jsonFilesDir, file);
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
try {
const stateName = path.parse(file).name;
const jsonData = JSON.parse(data);
let queryString = `INSERT INTO ${tableName} (state, county, population)\nVALUES\n`;
const insertStatements = jsonData.map(item => {
const { county, population } = item;
return `('${stateName.replace('\'', '\'\'')}', '${county.replace('\'', '\'\'')}', ${population}),`;
});
console.log(`-- File: ${file}`);
let lastCounty = insertStatements.pop();
lastCounty = lastCounty.replace('),', ');');
insertStatements.push(lastCounty);
queryString += insertStatements.join('\n');
fs.writeFileSync(`./sql-files/state-${stateName.replace(' ', '-')}.sql`, queryString);
} catch (parseError) {
console.error('Error parsing JSON:', parseError);
}
});
});
});