json-csv
This is a simple Node.JS module that can transorm JSON data to CSV. This version 4.x is in maintenance mode and will only receive critical updates. Please see @iwsio/json-csv-node for the latest, active version of this package.
Update v6 - June 2023
The latest version 6 just released in June 2023 and includes better type definitions along with ESM & CommonJS support. Read more about it on the v6 blog post.
Usage
Buffered
const jsoncsv = require('json-csv')
const csv = await jsoncsv.buffered(data, options)
jsoncsv.buffered(data, options, (err, csv) => {...}))
- data: Array of JS objects
- options: {fields: [], ...}
- optional callback: returns string result
Streaming
When using the streaming API, you can pipe data to it in object mode.
const jsoncsv = require('json-csv')
const readable = some_readable_source
readable
.pipe(jsoncsv.stream(options))
.pipe(something_else_writable)
})
Options
{
fields :
[
{
name: 'string',
label: 'string',
transform: function(value) { return value; }
}
],
fieldSeparator: ","
,ignoreHeader: false
,encoding: "utf8"
}
Advanced Example
Here, you can see we're using a deeper set of objects for our source data and we're using dot notation in the field definitions.
const items = [
{
downloaded: false,
contact: {
company: 'Widgets, LLC',
name: 'John Doe',
email: 'john@widgets.somewhere',
},
registration: {
year: 2013,
level: 3,
},
},
{
downloaded: true,
contact: {
company: 'Sprockets, LLC',
name: 'Jane Doe',
email: 'jane@sprockets.somewhere',
},
registration: {
year: 2013,
level: 2,
},
},
]
const options = {
fields: [
{
name: 'contact.company',
label: 'Company',
},
{
name: 'contact.name',
label: 'Name',
},
{
name: 'contact.email',
label: 'Email',
},
{
name: 'downloaded',
label: "Downloaded",
transform: (v) => v ? 'downloaded' : 'pending',
},
{
name: 'registration.year',
label: 'Year',
},
{
name: 'registration.level',
label: 'Level',
transform: (v) => {
switch (v) {
case 1: return 'Test 1'
case 2: return 'Test 2'
default: return 'Unknown'
}
},
},
],
}
async function writeCsv() {
try {
let result = await csv.buffered(items, options)
console.log(result)
} catch (err) {
console.error(err)
}
}
writeCsv()
Output
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