Skip to content

Commit 995ff6b

Browse files
authored
Add 'excludeKeys' option to json2csv. (#174)
1 parent c9df78c commit 995ff6b

File tree

6 files changed

+78
-5
lines changed

6 files changed

+78
-5
lines changed

README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,9 @@ Looking for examples? Check out the Wiki: [json-2-csv Wiki](https://github.com/m
6464
* `emptyFieldValue` - Any - Value that, if specified, will be substituted in for field values that are `undefined`, `null`, or an empty string.
6565
* Default: none
6666
* `excelBOM` - Boolean - Should a unicode character be prepended to allow Excel to open a UTF-8 encoded file with non-ASCII characters present.
67+
* `excludeKeys` - Array - Specify the keys that should be excluded from the output.
68+
* Default: `[]`
69+
* Note: When used with `unwindArrays`, arrays present at excluded key paths will not be unwound.
6770
* `expandArrayObjects` - Boolean - Should objects in array values be deep-converted to CSV?
6871
* Default: `false`
6972
* Example:
@@ -82,7 +85,7 @@ Looking for examples? Check out the Wiki: [json-2-csv Wiki](https://github.com/m
8285
* `false` uses the following keys:
8386
* `['specifications']`
8487
* Note: This may result in CSV output that does not map back exactly to the original JSON. See #102 for more information.
85-
* `keys` - Array - Specify the keys (as strings) that should be converted.
88+
* `keys` - Array - Specify the keys that should be converted.
8689
* Default: These will be auto-detected from your data by default.
8790
* Keys can either be specified as a String representing the key path that should be converted, or as an Object with the `key` property specifying the path. When specifying keys as an Object, you can also optionally specify a `title` which will be used for that column in the header. The list specified can contain a combination of Objects and Strings.
8891
* `[ 'key1', 'key2', ... ]`

lib/converter.d.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export interface ISharedOptions {
1919
excelBOM?: boolean;
2020

2121
/**
22-
* Specify the keys (as strings) that should be converted
22+
* Specify the keys that should be converted
2323
*
2424
* * If you have a nested object (ie. {info : {name: 'Mike'}}), then set this to ['info.name']
2525
* * If you want all keys to be converted, then specify null or don't specify the option to utilize the default.
@@ -87,6 +87,11 @@ export interface IFullOptions extends ISharedOptions {
8787
* @default false
8888
*/
8989
useDateIso8601Format?: boolean;
90+
91+
/**
92+
* Specify the keys that should be excluded from the output.
93+
*/
94+
excludeKeys?: string[];
9095
}
9196

9297
export function json2csv(data: object[],

lib/json2csv.js

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,19 @@ const Json2Csv = function(options) {
8181
}, 0);
8282
}
8383

84+
/**
85+
* If so specified, this filters the detected key paths to exclude any keys that have been specified
86+
* @param keyPaths {Array<String>}
87+
* @returns {Array<String>} filtered key paths
88+
*/
89+
function filterExcludedKeys(keyPaths) {
90+
if (options.excludeKeys) {
91+
return keyPaths.filter((keyPath) => !options.excludeKeys.includes(keyPath));
92+
}
93+
94+
return keyPaths;
95+
}
96+
8497
/**
8598
* If so specified, this sorts the header field names alphabetically
8699
* @param fieldNames {Array<String>}
@@ -157,11 +170,13 @@ const Json2Csv = function(options) {
157170

158171
if (options.keys && !options.unwindArrays) {
159172
return Promise.resolve(options.keys)
173+
.then(filterExcludedKeys)
160174
.then(sortHeaderFields);
161175
}
162176

163177
return getFieldNameList(data)
164178
.then(processSchemas)
179+
.then(filterExcludedKeys)
165180
.then(sortHeaderFields);
166181
}
167182

@@ -202,7 +217,7 @@ const Json2Csv = function(options) {
202217

203218
// If keys were provided, set the headerFields to the provided keys:
204219
if (options.keys) {
205-
params.headerFields = options.keys;
220+
params.headerFields = filterExcludedKeys(options.keys);
206221
}
207222
return params;
208223
});

package-lock.json

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
},
66
"name": "json-2-csv",
77
"description": "A JSON to CSV and CSV to JSON converter that natively supports sub-documents and auto-generates the CSV heading.",
8-
"version": "3.9.0",
8+
"version": "3.10.0",
99
"homepage": "https://mrodrig.github.io/json-2-csv",
1010
"repository": {
1111
"type": "git",

test/json2csv.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,56 @@ function runTests(jsonTestData, csvTestData) {
544544
]
545545
});
546546
});
547+
548+
it('should exclude specified keys from the output', (done) => {
549+
// Change the features array to be empty
550+
const updatedCsvPerOptions = csvTestData.arrayObjects.replace('features.cons,', '')
551+
.replace('"[""cost"",""time""]",', '')
552+
.replace(',,,', ',,');
553+
554+
converter.json2csv(jsonTestData.arrayObjects, (err, csv) => {
555+
if (err) done(err);
556+
csv.should.equal(updatedCsvPerOptions);
557+
done();
558+
}, {
559+
expandArrayObjects: true,
560+
keys: ['name', 'features.name', 'features.pros', 'features.cons', 'downloads'],
561+
excludeKeys: ['features.cons']
562+
});
563+
});
564+
565+
it('should exclude specified keys from the output when unwinding arrays', (done) => {
566+
const updatedCsv = csvTestData.unwind.replace(',data.options.name', '')
567+
.replace(/,MacBook (Pro|Air) \d+/g, '')
568+
.replace(/,(Super|Turbo)charger/g, '')
569+
// De-duplicate the lines since the field isn't unwound due to being excluded
570+
.replace('5cf7ca3616c91100018844af,Computers\n', '')
571+
.replace('5cf7ca3616c91100018844bf,Cars\n', '');
572+
573+
converter.json2csv(jsonTestData.unwind, (err, csv) => {
574+
if (err) done(err);
575+
csv.should.equal(updatedCsv);
576+
done();
577+
}, {
578+
unwindArrays: true,
579+
excludeKeys: ['data.options.name', 'data.options']
580+
});
581+
});
582+
583+
it('should exclude specified deeply nested key from the output when unwinding arrays', (done) => {
584+
const updatedCsv = csvTestData.unwind.replace(',data.options.name', '')
585+
.replace(/,MacBook (Pro|Air) \d+/g, '')
586+
.replace(/,(Super|Turbo)charger/g, '');
587+
588+
converter.json2csv(jsonTestData.unwind, (err, csv) => {
589+
if (err) done(err);
590+
csv.should.equal(updatedCsv);
591+
done();
592+
}, {
593+
unwindArrays: true,
594+
excludeKeys: ['data.options.name']
595+
});
596+
});
547597
});
548598
});
549599

0 commit comments

Comments
 (0)