Skip to content

Commit

Permalink
Use all toplevel fields if fields not specified
Browse files Browse the repository at this point in the history
Closes #41

This does not support nested fields. If you have nested fields, the
object associated with the toplevel field will be serialized as JSON
and you will have a JSON string in your CSV.
  • Loading branch information
Ilya Radchenko committed Jul 16, 2015
1 parent 6f017a3 commit bac5066
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 7 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ or [use it from the CLI](https://github.com/zemirco/json2csv#command-line-interf

- `options` - **Required**; Options hash.
- `data` - **Required**; Array of JSON objects.
- `fields` - **Required**; Array of Strings, JSON attribute names to use as columns.
- `fields` - Array of Strings, JSON attribute names to use as columns. Defaults to toplevel JSON attributes.
- `fieldNames` Array of Strings, names for the fields at the same indexes.
Must be the same length as `fields` array.
- `del` - String, delimiter of columns. Defaults to `,` if not specified.
Expand Down
6 changes: 1 addition & 5 deletions bin/json2csv.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,6 @@ program
.option('-p, --pretty', 'Use only when printing to console. Logs output in pretty tables.')
.parse(process.argv);

if(!program.fields && !program.fieldList) {
throw new Error('Please specify fields with -f or a list of fields with -l. See json2csv --help');
}

function getFields(callback) {
var fields;

Expand All @@ -41,7 +37,7 @@ function getFields(callback) {
callback(null, fields);
});
} else {
fields = program.fields.split(',');
fields = program.fields ? program.fields.split(',') : undefined;
callback(null, fields);
}
}
Expand Down
6 changes: 5 additions & 1 deletion lib/json2csv.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,16 @@ module.exports = function (params, callback) {
function checkParams(params, callback) {
// if data is an Object, not in array [{}], then just create 1 item array.
// So from now all data in array of object format.
if (!(params.data instanceof Array)) {
if (!Array.isArray(params.data)) {
var ar = [];
ar[0] = params.data;
params.data = ar;
}

if (!params.fields && params.data && params.data.length) {
params.fields = Object.keys(params.data[0]);
}

//#check fieldNames
if (params.fieldNames && params.fieldNames.length !== params.fields.length) {
callback(new Error('fieldNames and fields should be of the same length, if fieldNames is provided.'));
Expand Down

0 comments on commit bac5066

Please sign in to comment.