diff options
| author | Bobby <[email protected]> | 2022-01-28 16:51:58 -0500 |
|---|---|---|
| committer | Bobby <[email protected]> | 2022-01-28 16:51:58 -0500 |
| commit | fae750e3027a6377e9de8dafe278efce4d262df4 (patch) | |
| tree | 13f919f29e17012217b0039e307e6535b2c86926 | |
| parent | 71a47064e453e59973dfc67be1915a4395c97bec (diff) | |
| download | izuku.js-fae750e3027a6377e9de8dafe278efce4d262df4.tar.xz izuku.js-fae750e3027a6377e9de8dafe278efce4d262df4.zip | |
feat: function to save to JSON
| -rw-r--r-- | src/index.ts | 2 | ||||
| -rw-r--r-- | src/lib/export.ts | 44 | ||||
| -rw-r--r-- | tests/simple.test.ts | 2 |
3 files changed, 47 insertions, 1 deletions
diff --git a/src/index.ts b/src/index.ts index 394fe93..8214328 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,6 +9,7 @@ import { import { show, head, tail } from './lib/display'; import { getSize, info } from './lib/info'; import { flatten, fromJSON, fromCSV, searchValue } from './lib/data'; +import { toJSON } from './lib/export'; import { isArrayOfType, range, flattenJSON } from './helpers/arrayFunctions'; class Izuku { @@ -81,6 +82,7 @@ class Izuku { return new Izuku(rowdata, this.columns); }; public title = title; + public toJSON = toJSON; } class Frame extends Izuku { diff --git a/src/lib/export.ts b/src/lib/export.ts new file mode 100644 index 0000000..137e534 --- /dev/null +++ b/src/lib/export.ts @@ -0,0 +1,44 @@ +import { Frame } from '../index'; +import { writeFileSync } from 'fs'; + +/** + * toJSON - converts frame to JSON file, takes a path to save the file. Path is optional. If no path is provided, the file is saved in the current directory + * @param frame: the frame to be converted + * @param path: @optional the path to save the file + * @param filename: @optional the name of the file + */ +export function toJSON(this: Frame, path?: string, filename?: string): void { + const data = this.rowdata; + const header = this.columns; + + // create a json object, with keys as the header and values as the row data + const json = data.map((row: any[]) => { + const obj: any = {}; + for (let i = 0; i < header.length; i++) { + if (row[i]) { + obj[header[i]] = row[i]; + } + } + return obj; + }); + + // save the json object to a file + if (path) { + writeFileSync( + `${path}/${filename ? `${filename}` : 'data'}.json`, + JSON.stringify(json) + ); + } else { + writeFileSync( + `${filename ? `${filename}` : 'data'}.json`, + JSON.stringify(json) + ); + } + + // console.log the file path + console.log( + `${filename ? `${filename}` : 'data'}.json saved at ${ + path ? path : 'root level' + }.` + ); +} diff --git a/tests/simple.test.ts b/tests/simple.test.ts index dffde21..8957d11 100644 --- a/tests/simple.test.ts +++ b/tests/simple.test.ts @@ -5,6 +5,6 @@ const frame = new Frame(data, header); describe('Print a frame', () => { it('should print a frame', () => { - frame.title('Simple Frame').show(); + frame.title('Simple Frame').toJSON(undefined, 'hello'); }); }); |
