Skip to content

Commit d234b04

Browse files
committed
Add undefinedReplacement option to diffJson
1 parent 870aa15 commit d234b04

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

src/diff/json.js

+10-3
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,21 @@ jsonDiff.useLongestToken = true;
1111

1212
jsonDiff.tokenize = lineDiff.tokenize;
1313
jsonDiff.castInput = function(value) {
14-
return typeof value === 'string' ? value : JSON.stringify(canonicalize(value), undefined, ' ');
14+
const {undefinedReplacement} = this.options;
15+
16+
return typeof value === 'string' ? value : JSON.stringify(canonicalize(value), function(k, v) {
17+
if (typeof v === 'undefined') {
18+
return undefinedReplacement;
19+
}
20+
21+
return v;
22+
}, ' ');
1523
};
1624
jsonDiff.equals = function(left, right) {
1725
return Diff.prototype.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
1826
};
1927

20-
export function diffJson(oldObj, newObj, callback) { return jsonDiff.diff(oldObj, newObj, callback); }
21-
28+
export function diffJson(oldObj, newObj, options) { return jsonDiff.diff(oldObj, newObj, options); }
2229

2330
// This function handles the presence of circular references by bailing out when encountering an
2431
// object that is already on the "stack" of items being processed.

test/diff/json.js

+9
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,15 @@ describe('diff/json', function() {
6666
)).to.eql([
6767
{ count: 4, value: '{\n "a": 123,\n "b": 456\n}' }
6868
]);
69+
expect(diffJson(
70+
{a: 123, b: 456, c: undefined},
71+
{a: 123, b: 456},
72+
{undefinedReplacement: null}
73+
)).to.eql([
74+
{ count: 3, value: '{\n "a": 123,\n "b": 456,\n' },
75+
{ count: 1, value: ' "c": null\n', added: undefined, removed: true },
76+
{ count: 1, value: '}' }
77+
]);
6978
});
7079

7180
it('should accept already stringified JSON', function() {

0 commit comments

Comments
 (0)