Skip to content
Closed
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
46 changes: 35 additions & 11 deletions src/TreeInterpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,18 +165,18 @@ export class TreeInterpreter {
return null;
}

const results: JSONArray = [];
for (const elem of base) {
const matched = this.visit(condition, elem);
if (isFalse(matched)) {
continue;
}
const result = this.visit(right, elem) as JSONValue;
if (result !== null) {
results.push(result);
}
const hasArrayElements = base.some(elem => Array.isArray(elem));
if (!hasArrayElements) {
return this.applyFilterProjection(base, condition, right);
}
return results;

return base
.map(elem =>
Array.isArray(elem)
? this.applyFilterProjection(elem, condition, right)
: this.applyFilterToElement(elem, condition, right),
)
.filter(result => result !== null);
}
case 'Arithmetic': {
const first = this.visit(node.left, value) as JSONValue;
Expand Down Expand Up @@ -351,6 +351,30 @@ export class TreeInterpreter {
}
return result;
}

private applyFilterProjection(elements: JSONArray, condition: ExpressionNode, right: ExpressionNode): JSONArray {
const results: JSONArray = [];
for (const elem of elements) {
const matched = this.visit(condition, elem);
if (isFalse(matched)) {
continue;
}
const result = this.visit(right, elem) as JSONValue;
if (result !== null) {
results.push(result);
}
}
return results;
}

private applyFilterToElement(elem: JSONValue, condition: ExpressionNode, right: ExpressionNode): JSONValue {
const matched = this.visit(condition, elem);
if (isFalse(matched)) {
return null;
}
const result = this.visit(right, elem) as JSONValue;
return result !== null ? result : null;
}
}

export const TreeInterpreterInstance = new TreeInterpreter();
Expand Down
16 changes: 16 additions & 0 deletions test/jmespath-interpreter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,20 @@ describe('Searches compiled ast', () => {
it('search a compiled expression', () => {
expect(search({ foo: { bar: 'BAZ' } }, 'foo.bar')).toEqual('BAZ');
});

it('handles filter projections with array field access', () => {
const data = [
{
stack: '',
branch: ['one/', 'two/'],
},
{
stack: null,
branch: ['three/', 'four/'],
},
];

const result = search(data, "[?stack==''].branch[?starts_with(@, 'one')]");
expect(result).toEqual([['one/']]);
});
});