-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv2json.ts
45 lines (35 loc) · 919 Bytes
/
csv2json.ts
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
import { parse } from "https://deno.land/[email protected]/flags/mod.ts";
import { readCSV, readCSVObjects } from "https://deno.land/x/csv/mod.ts";
const { args } = Deno;
const parsedArgs = parse(args);
const requiredArgs = [
"input",
];
requiredArgs.forEach((arg) => {
if (!parsedArgs[arg]) {
throw new Error("Missing required argument: " + arg);
}
});
const { input, output, columns } = parsedArgs;
const csvFile = await Deno.open(input);
const outputArray = [];
for await (const obj of readCSVObjects(csvFile)) {
if (columns) {
const filtered = columns.split(",").reduce(
(carry: Record<string, string>, col: string) => {
if(obj[col])
carry[col] = obj[col];
return carry;
},
{}
);
outputArray.push(filtered);
} else {
outputArray.push(obj);
}
}
csvFile.close();
if(!output){
console.log(JSON.stringify(outputArray));
}
Deno.exit();