Skip to content

Commit 5d670ae

Browse files
authored
Merge pull request #372 from nathangobinet/master
🐛 Fix JsonPatch Formatter: Properly escape property name
2 parents 4c0eee3 + 4752181 commit 5d670ae

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

packages/jsondiffpatch/src/formatters/jsonpatch.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ interface JSONFormatterContext extends BaseFormatterContext {
5353
pushMoveOp: (to: number) => void;
5454
currentPath: () => string;
5555
toPath: (to: number) => string;
56+
buildPath: (path: (string | number)[]) => string;
57+
escapePath: (path: string | number) => string;
5658
}
5759

5860
class JSONFormatter extends BaseFormatter<JSONFormatterContext, Op[]> {
@@ -89,13 +91,23 @@ class JSONFormatter extends BaseFormatter<JSONFormatterContext, Op[]> {
8991
};
9092

9193
context.currentPath = function () {
92-
return `/${this.path!.join('/')}`;
94+
return `/${this.buildPath!(this.path!)}`;
9395
};
9496

9597
context.toPath = function (toPath) {
9698
const to = this.path!.slice();
9799
to[to.length - 1] = toPath;
98-
return `/${to.join('/')}`;
100+
return `/${this.buildPath!(to)}`;
101+
};
102+
103+
context.buildPath = function (path: (string | number)[]) {
104+
return path.map((path) => this.escapePath!(path)).join('/');
105+
};
106+
107+
context.escapePath = function (path: string | number) {
108+
if (typeof path !== 'string') return path.toString();
109+
if (path.indexOf('/') === -1 && path.indexOf('~') === -1) return path;
110+
return path.replace(/~/g, '~0').replace(/\//g, '~1');
99111
};
100112
}
101113

packages/jsondiffpatch/test/index.spec.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -606,6 +606,12 @@ describe('DiffPatcher', () => {
606606
});
607607
expectFormat(before, after, diff);
608608
});
609+
610+
it('should escape the property name', () => {
611+
expectFormat({ 'tree/item': 1 }, { 'tree/item': 2 }, [
612+
replaceOp('/tree~1item', 2),
613+
]);
614+
});
609615
});
610616

611617
describe('html', () => {

0 commit comments

Comments
 (0)