Skip to content

Commit f577fb5

Browse files
authored
fix(slice): explicit zero end no longer returns the whole array (#265)
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.
1 parent 3a471a0 commit f577fb5

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

src/jsonpath.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -608,7 +608,7 @@ JSONPath.prototype._slice = function (
608608
const len = val.length, parts = loc.split(':'),
609609
step = (parts[2] && Number.parseInt(parts[2])) || 1;
610610
let start = (parts[0] && Number.parseInt(parts[0])) || 0,
611-
end = (parts[1] && Number.parseInt(parts[1])) || len;
611+
end = parts[1] ? Number.parseInt(parts[1]) : len;
612612
start = (start < 0) ? Math.max(0, start + len) : Math.min(len, start);
613613
end = (end < 0) ? Math.max(0, end + len) : Math.min(len, end);
614614
const ret = [];

test/test.slice.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,25 @@ describe('JSONPath - slice', function () {
4242
});
4343
assert.deepEqual(result, expected);
4444
});
45+
46+
it('should return empty array for a slice with an explicit zero end', function () {
47+
const jsonWithChildren = {
48+
"name": "root",
49+
"children": [
50+
{a: 1}, {a: 2}, {a: 3}, {a: 4}, {a: 5}, {a: 6}
51+
]
52+
};
53+
assert.deepEqual(jsonpath({
54+
json: jsonWithChildren,
55+
path: '$.children[:0]'
56+
}), []);
57+
assert.deepEqual(jsonpath({
58+
json: jsonWithChildren,
59+
path: '$.children[2:0]'
60+
}), []);
61+
assert.deepEqual(jsonpath({
62+
json: jsonWithChildren,
63+
path: '$.children[0:0]'
64+
}), []);
65+
});
4566
});

0 commit comments

Comments
 (0)