Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/jsonpath.js
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,9 @@ class JSONPathClass {
val, /** @type {string|number} */ (loc), callback,
hasArrExpr
));
} else if (typeof loc !== 'string') {
// A number or other value (e.g., from `[(@.length-1)]`) which is
// not a property of this value, so there is nothing to follow
// eslint-disable-next-line unicorn/prefer-switch -- Part of larger `if`
} else if (loc === '*') { // all child properties
this._walk(val, (m) => {
Expand Down
37 changes: 37 additions & 0 deletions test/test.examples.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,43 @@ checkBuiltInVMAndNodeVM(function (vmType, setBuiltInState) {
assert.deepEqual(result, expected);
});

it('last property of entire tree (index which does not exist)', () => {
// `-1` is not an index of an empty array, so nothing is found
assert.deepEqual(jsonpath({
json: {items: []}, path: '$.items[(@.length-1)]'
}), []);
// Other arrays in the tree are still searched
assert.deepEqual(jsonpath({
json: {items: [], other: {items: [5, 6]}},
path: '$..items[(@.length-1)]'
}), [6]);
assert.deepEqual(jsonpath({
json: {a: [], b: [1, 2]}, path: '$.*[(@.length-1)]'
}), [2]);
assert.deepEqual(jsonpath({
json: {items: [1, 2]}, path: '$.items[(@.length+5)]'
}), []);
// Results which cannot be property names (here `NaN`, `null`
// and `true`) find nothing, including after a slice (#181)
const obj = {o: {a: 1}};
assert.deepEqual(jsonpath({
json: obj, path: '$.o[(@.length-1)]'
}), []);
assert.deepEqual(jsonpath({json: obj, path: '$.o[(null)]'}), []);
assert.deepEqual(jsonpath({json: obj, path: '$.o[(true)]'}), []);
assert.deepEqual(jsonpath({
json: {stores: [{name: 'a'}, {name: 'b'}, {name: 'c'}]},
path: '$.stores[0:3:2][(@.length-1)].name'
}), []);
// Properties with those names are still found
assert.deepEqual(jsonpath({
json: {o: {null: 'N', true: 'T'}}, path: '$.o[(null)]'
}), ['N']);
assert.deepEqual(jsonpath({
json: {o: {null: 'N', true: 'T'}}, path: '$.o[(true)]'
}), ['T']);
});

it('range of property of entire tree', () => {
const books = json.store.book;
const expected = [books[0], books[1]];
Expand Down
Loading