-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.js
47 lines (36 loc) · 1.35 KB
/
convert.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
// This script can only be suitable for the data records which is less than
2000;
const fs = require("fs");
function convert(collectionName, sourceFile, query, resultFile) {
fs.readFile(sourceFile, "utf8", (err, data) => {
if (err) {
console.log("Source file read failed:", err);
return;
}
const json = JSON.parse(data);
const response = json.reduce((acc, cur, index) => {
const key = cur[collectionName].id.toString();
const value = cur[collectionName];
const valueString = JSON.stringify(value);
cur = ('("' + key + '", ' + valueString + ")").replace(/\\/g, "");
comma = index === json.length - 1 ? "" : ", ";
acc += cur + comma;
return acc;
}, "");
if (response) {
const final = `${query} ${response}`;
fs.writeFile(resultFile, final, function (err) {
if (err) return console.log(err);
console.log(`Generated data have been saved into ${resultFile}`);
});
}
});
}
// start converting by fill in the details of sourceFile, query and resultFile
// Example for bucket-name > scope-name > collection-name
// convert(
// "nested-object-name", // can be optional, depends on how your object looks like
// "./source-file-name.json",
// "INSERT INTO `bucket-name`.`scope-name`.`collection-name`(KEY, VALUE) VALUES ",
// "generated-query.txt"
// );