![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
jsonexport
Advanced tools
The jsonexport npm package is a utility that allows you to convert JSON data into CSV format. It is particularly useful for exporting data from JSON APIs or databases into a format that can be easily imported into spreadsheet applications like Microsoft Excel or Google Sheets.
Basic JSON to CSV Conversion
This feature allows you to convert a simple JSON array into CSV format. The code sample demonstrates how to convert an array of JSON objects into a CSV string.
const jsonexport = require('jsonexport');
const data = [{"name":"John","age":30},{"name":"Jane","age":25}];
jsonexport(data, function(err, csv){
if(err) return console.error(err);
console.log(csv);
});
Nested JSON to CSV Conversion
This feature allows you to convert nested JSON objects into CSV format. The code sample demonstrates how to handle nested JSON structures and convert them into a flat CSV format.
const jsonexport = require('jsonexport');
const data = [{"name":"John","age":30,"address":{"city":"New York","state":"NY"}},{"name":"Jane","age":25,"address":{"city":"San Francisco","state":"CA"}}];
jsonexport(data, function(err, csv){
if(err) return console.error(err);
console.log(csv);
});
Custom Delimiters
This feature allows you to specify custom delimiters for the CSV output. The code sample demonstrates how to use a semicolon as the delimiter instead of the default comma.
const jsonexport = require('jsonexport');
const data = [{"name":"John","age":30},{"name":"Jane","age":25}];
const options = {delimiter: ';'};
jsonexport(data, options, function(err, csv){
if(err) return console.error(err);
console.log(csv);
});
The json2csv package is another popular library for converting JSON to CSV. It offers similar functionalities to jsonexport, including support for nested JSON objects and custom delimiters. However, json2csv provides more advanced features like field selection, field renaming, and data transformation.
The csv-writer package is a versatile library for writing CSV files. While it does not directly convert JSON to CSV, it allows you to write CSV files from JavaScript objects, making it a good alternative for more complex CSV writing needs. It offers features like custom headers, field transformations, and support for different CSV formats.
✔ easy to use 👌 (should work as expected without much customization)️
✔ extendable 🕺 (many options to customize the output)
✔️ tiny 🐜 (0 dependencies)
✔ scalable 💪 (works with big files using Streams)
✔ fast ⚡
Installation command is npm install jsonexport
.
Run tests with npm test
.
const jsonexport = require('jsonexport');
jsonexport({lang: 'Node.js', module: 'jsonexport'}, {rowDelimiter: '|'}, function(err, csv){
if (err) return console.error(err);
console.log(csv);
});
Global installation command is npm install -g jsonexport
.
Convert JSON to CSV using cat data.json | jsonexport
or jsonexport data.json
Usage: jsonexport <JSON filename> <CSV filename>
Use the code in the folder named dist to run jsonexport in the browser
Webpack
const jsonexport = require("jsonexport/dist")
Typescript
import * as jsonexport from "jsonexport/dist"
const jsonexport = require('jsonexport');
const fs = require('fs');
const reader = fs.createReadStream('data.json');
const writer = fs.createWriteStream('out.csv');
reader.pipe(jsonexport()).pipe(writer);
const jsonexport = require('jsonexport')
try {
const csv = await jsonexport({lang: 'Node.js', module: 'jsonexport'}, {rowDelimiter: '|'});
} catch (err) {
console.error(err);
}
const jsonexport = require('jsonexport');
const contacts = [{
name: 'Bob',
lastname: 'Smith'
},{
name: 'James',
lastname: 'David'
},{
name: 'Robert',
lastname: 'Miller'
},{
name: 'David',
lastname: 'Martin'
}];
jsonexport(contacts, function(err, csv){
if (err) return console.error(err);
console.log(csv);
});
name,lastname
Bob,Smith
James,David
Robert,Miller
David,Martin
const jsonexport = require('jsonexport');
const contacts = [{
name: 'Bob',
lastname: 'Smith',
family: {
name: 'Peter',
type: 'Father'
}
},{
name: 'James',
lastname: 'David',
family:{
name: 'Julie',
type: 'Mother'
}
},{
name: 'Robert',
lastname: 'Miller',
family: null,
location: [1231,3214,4214]
},{
name: 'David',
lastname: 'Martin',
nickname: 'dmartin'
}];
jsonexport(contacts, function(err, csv){
if (err) return console.error(err);
console.log(csv);
});
name,lastname,family.name,family.type,family,location,nickname
Bob,Smith,Peter,Father
James,David,Julie,Mother
Robert,Miller,,,,1231;3214;4214
David,Martin,,,,,dmartin
const jsonexport = require('jsonexport');
const stats = {
cars: 12,
roads: 5,
traffic: 'slow'
};
jsonexport(stats, function(err, csv){
if(err) return console.error(err);
console.log(csv);
});
cars,12
roads,5
traffic,slow
const jsonexport = require('jsonexport');
const stats = {
cars: 12,
roads: 5,
traffic: 'slow',
speed: {
max: 123,
avg: 20,
min: 5
},
size: [10,20]
};
jsonexport(stats, function(err, csv){
if(err) return console.error(err);
console.log(csv);
});
cars,12
roads,5
traffic,slow
speed.max,123
speed.avg,20
speed.min,5
size,10;20
In order to get the most of out of this module, you can customize many parameters and functions.
headerPathString
- String
Used to create the propriety path, defaults to .
example contact: {name: 'example}
= contact.name
fillGaps
- Boolean
Set this option if don't want to have empty cells in case of an object with multiple nested items (array prop), defaults to false
Issue #22fillTopRow
- Boolean
try filling top rows first for unpopular colums, defaults to false
headers
- Array
Used to set a custom header order, defaults to []
example ['lastname', 'name']
rename
- Array
Used to set a custom header text, defaults to []
example ['Last Name', 'Name']
mapHeaders
- Function
Post-process headers after they are calculated with delimiters, example mapHeaders: (header) => header.replace(/foo\./, '')
rowDelimiter
- String
Change the file row delimiter
,
(cvs format).\t
for xls format.;
for (windows excel .csv format).textDelimiter
- String
The character used to escape the text content if needed (default to "
)forceTextDelimiter
- Boolean
Set this option to true to wrap every data item and header in the textDelimiter. Defaults to false
endOfLine
- String
Replace the OS default EOL.mainPathItem
- String
Every header will have the mainPathItem
as the base.arrayPathString
- String
This is used to output primitive arrays in a single column, defaults to ;
booleanTrueString
- String
Will be used instead of true
.booleanFalseString
- String
Will be used instead of false
.includeHeaders
- Boolean
Set this option to false to hide the CSV headers.undefinedString
- String
If you want to display a custom value for undefined strings, use this option. Defaults to
.verticalOutput
- Boolean
Set this option to false to create a horizontal output for JSON Objects, headers in the first row, values in the second.typeHandlers
- {typeName:(value, index, parent)=>any
A key map of constructors used to match by instance to create a value using the defined function (see example)Define types by constructors and what function to run when that type is matched
const jsonexport = require('jsonexport');
//data
const contacts = {
'a' : Buffer.from('a2b', 'utf8'),
'b' : Buffer.from('other field', 'utf8'),
'x' : 22,
'z' : function(){return 'bad ace'}
};
const options = {
//definitions to type cast
typeHandlers: {
Array:function(value,index,parent){
return 'replaced-array';
},
Boolean:function(value,index,parent){
return 'replaced-boolean';
},
Function:function(value,index,parent){
return value();
},
Number:function(value,index,parent){
return 'replaced-number';
},
String:function(value,index,parent){
return 'replaced-string';
},
Buffer:function(value,index,parent){
return value.toString();
}
}
};
jsonexport(contacts, options, function(err, csv) {
if (err) return console.error(err);
console.log(csv);
});
The output would be:
a,a2b
b,other field
x,replaced-number
z,bad ace
Date typeHandler?
var date = new Date();
jsonexport({
a: date,
b: true
}, {
typeHandlers: {
Object: (value, name) => {
if (value instanceof Date) return date.toLocaleString();
return value;
}
}
}, (err, csv) => {
if (err) return console.error(err);
console.log(csv);
});
When using typeHandlers, Do NOT do this
const options = {
typeHandlers: {
Object:function(value, index, parent){
return 'EVERYTHING IS AN OBJECT';
}
}
};
It is NOT an error, however the recursive result becomes illegable functionality strings
FAQs
Makes easy to convert JSON to CSV
We found that jsonexport demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.