Skip to content

Commit

Permalink
feat: add jsonReviver option for parsing
Browse files Browse the repository at this point in the history
CLOSES #35
  • Loading branch information
joshswan committed Feb 27, 2024
1 parent b67f25e commit 6517468
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
2 changes: 2 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ declare module 'gulp-merge-json' {
mergeArrays?: boolean;
/** Custom merge function for use with mergeWith */
customizer?: (objValue: obj, srcValue: obj, key?: string, object?: obj, source?: obj, stack?: any) => any;
/** Custom JSON reviver function passed to parse */
jsonReviver?: (key: string, value: any) => any;
/** Custom JSON replacer function passed to stringify */
jsonReplacer?: (key: string, value: any) => any;
/**
Expand Down
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ module.exports = function mergeJson(opts) {
mergeArrays: true,
customizer: null,
jsonReplacer: null,
jsonReviver: null,
jsonSpace: '\t',
json5: false,
...opts,
Expand Down Expand Up @@ -81,7 +82,7 @@ module.exports = function mergeJson(opts) {
}

try {
parsed = jsonLib.parse(file.contents.toString('utf8'));
parsed = jsonLib.parse(file.contents.toString('utf8'), options.jsonReviver);
} catch (err) {
err.message = `Error while parsing ${file.path}: ${err.message}`;
return this.emit('error', new PluginError(PLUGIN_NAME, err));
Expand Down
19 changes: 19 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,25 @@ describe('gulp-merge-json', () => {
stream.end();
});

test('uses jsonReviver when parsing if supplied in options', (done) => {
const stream = gulp.src(['test/json/test1.json', 'test/json/test2.json']).pipe(merge({
jsonReviver: (key, value) => {
if (key === 'pet') {
return undefined;
}

return value;
},
}));

stream.on('data', (file) => {
const expected = ['{', '\t"name": "Josh",', '\t"tags": [', '\t\t"awesome",', '\t\t"fun"', '\t],', '\t"place": "San Francisco",', '\t"settings": {', '\t\t"likesSleep": true', '\t}', '}'].join('\n');

expect(file.contents.toString()).toBe(expected);
done();
});
});

test('uses jsonReplacer when stringifying if supplied in options', (done) => {
const stream = gulp.src(['test/json/test1.json', 'test/json/test2.json']).pipe(merge({
jsonReplacer: (key, value) => {
Expand Down

1 comment on commit 6517468

@steverep
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

Please sign in to comment.