@iwsio/json-csv-core
Simple CSV export module that can export a rich JSON array of objects to CSV.
This is a core project built for node AND browser. My goals here were to open up the audience for the predecessor package json-csv
, which will still serve as the Node only extension of this one supporting features like Stream/Readable in Node.
This core library will focus on the buffered and single object -> CSV functionality.
Getting Started
Install
npm i @iwsio/json-csv-core
Import with named or default exports.
import { buffered } from '@iwsio/json-csv-core'
import buffered from '@iwsio/json-csv-core'
In Typescript, buffered
is defined as:
declare buffered = (data: any[], options: ExporterOptions) => string;
import { buffered } from '@iwsio/json-csv-core'
const data = [
{
field1: 'test',
field2: 123,
thing: {
field3: true,
field4: 'test'
}
},
{field1: 'test', field2: 123, thing: { field3: true, field4: 'test'}},
{field1: 'test', field2: 123, thing: { field3: false, field4: 'test'}},
{field1: 'test', field2: 123, thing: { field3: true, field4: 'test'}}
]
const options = {
fields: [
{name: 'field1'}, // regular field by name
{name: 'field2'},
// using dot notation, we can specify which value to use.
// provide a transform if you want the value to be modified for output.
{name: 'thing.field3', label: 'field3', transform: (v) => v ? 'yes' : 'no'},
{name: 'thing.field4', label: 'field4'},
]
}
const csv = jsoncsv(data, options)
field1,field2,field3,field4
test,123,yes,test
test,123,yes,test
test,123,no,test
test,123,yes,test
Options
{
fields: [
{
name: 'string',
label: 'string',
transform: function(value) { return value; }
}
],
fieldSeparator: ',',
ignoreHeader: false
}
Simple CSV
Run the samples.
node samples/simple.mjs
Outputs
"Name",Email,Amount
"fred",fred@somewhere,1.02
"jo",jo@somewhere,1.02
"jo with a comma,",jo@somewhere,1.02
"jo with a quote""",jo@somewhere,1.02
Advanced CSV
node samples/advanced.mjs
Outputs
Company,Name,Email,Downloaded,Year,Level
"Widgets, LLC",John Doe,john@widgets.somewhere,pending,2013,Unknown
"Sprockets, LLC",Jane Doe,jane@sprockets.somewhere,downloaded,2013,Test 2