1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { Statement } from "https://esm.town/v/postpostscript/sqliteBuilder";
import { ResultSet } from "https://esm.town/v/std/sqlite?v=6";
import { Parser } from "npm:@json2csv/plainjs";
export const sqlToJSON = (result: ResultSet) => {
const { columns, rows } = result;
return rows.map(row =>
columns.reduce((obj, col, index) => {
obj[col] = row[index];
return obj;
}, {})
);
};
export const sqlToCSV = (result: ResultSet) => {
try {
const { columns, rows } = result;
const records = sqlToJSON(result);
return new Parser({ fields: columns }).parse(records);
} catch (error) {
return error.message;
}
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
1
pomdtr avatar

as discussed in discord, the sqlToCSV val will not work if a column contains a comma.

I use this lib to handle edge cases in the VS Code Extension: https://www.npmjs.com/package/@json2csv/plainjs

v23
June 30, 2024