From a2f559e8c38f6a5134c6d9488f3f56fa519a17d2 Mon Sep 17 00:00:00 2001 From: Yarchik Date: Tue, 23 Jun 2026 01:21:46 +0100 Subject: [PATCH] fix(slice): explicit zero end no longer returns the whole array A slice with an explicit `0` end (e.g. `$[:0]`, `$[2:0]`) returned the entire array instead of an empty result. `end` was computed with `(parts[1] && Number.parseInt(parts[1])) || len`, so a parsed end of `0` is falsy and got replaced by the array length. Treat an omitted end (empty string) as the length and parse any explicit value, including 0. --- src/jsonpath.js | 2 +- test/test.slice.js | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/jsonpath.js b/src/jsonpath.js index 15be4268..e2bdbb57 100644 --- a/src/jsonpath.js +++ b/src/jsonpath.js @@ -608,7 +608,7 @@ JSONPath.prototype._slice = function ( const len = val.length, parts = loc.split(':'), step = (parts[2] && Number.parseInt(parts[2])) || 1; let start = (parts[0] && Number.parseInt(parts[0])) || 0, - end = (parts[1] && Number.parseInt(parts[1])) || len; + end = parts[1] ? Number.parseInt(parts[1]) : len; start = (start < 0) ? Math.max(0, start + len) : Math.min(len, start); end = (end < 0) ? Math.max(0, end + len) : Math.min(len, end); const ret = []; diff --git a/test/test.slice.js b/test/test.slice.js index afab5bd4..5034642c 100644 --- a/test/test.slice.js +++ b/test/test.slice.js @@ -42,4 +42,25 @@ describe('JSONPath - slice', function () { }); assert.deepEqual(result, expected); }); + + it('should return empty array for a slice with an explicit zero end', function () { + const jsonWithChildren = { + "name": "root", + "children": [ + {a: 1}, {a: 2}, {a: 3}, {a: 4}, {a: 5}, {a: 6} + ] + }; + assert.deepEqual(jsonpath({ + json: jsonWithChildren, + path: '$.children[:0]' + }), []); + assert.deepEqual(jsonpath({ + json: jsonWithChildren, + path: '$.children[2:0]' + }), []); + assert.deepEqual(jsonpath({ + json: jsonWithChildren, + path: '$.children[0:0]' + }), []); + }); });