Skip to content

Commit adbd2a2

Browse files
committed
Implement JEP-10: Slice Projections
Same implementation as python, this implements JEP-10 from jmespath/jmespath.site#3.
1 parent cd4a1e2 commit adbd2a2

File tree

2 files changed

+63
-2
lines changed

2 files changed

+63
-2
lines changed

jmespath.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -530,7 +530,8 @@
530530

531531
nudLbracket: function() {
532532
if (this.lookahead(0) === "Number" || this.lookahead(0) === "Colon") {
533-
return this.parseIndexExpression();
533+
var right = this.parseIndexExpression();
534+
return this.projectIfSlice({type: "Identity"}, right);
534535
} else if (this.lookahead(0) === "Star" &&
535536
this.lookahead(1) === "Rbracket") {
536537
this.advance();
@@ -556,6 +557,18 @@
556557
}
557558
},
558559

560+
projectIfSlice: function(left, right) {
561+
var indexExpr = {type: "IndexExpression", children: [left, right]};
562+
if (right.type === "Slice") {
563+
return {
564+
type: "Projection",
565+
children: [indexExpr, this.parseProjectionRHS(this.bindingPower.Star)]
566+
};
567+
} else {
568+
return indexExpr;
569+
}
570+
},
571+
559572
parseSliceExpression: function() {
560573
// [start:end:step] where each part is optional, as well as the last
561574
// colon.
@@ -653,7 +666,7 @@
653666
var right;
654667
if (token.type === "Number" || token.type === "Colon") {
655668
right = this.parseIndexExpression();
656-
return {type: "IndexExpression", children: [left, right]};
669+
return this.projectIfSlice(left, right);
657670
} else {
658671
this.match("Star");
659672
this.match("Rbracket");

test/compliance/slice.json

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,4 +127,52 @@
127127
"error": "syntax"
128128
}
129129
]
130+
}, {
131+
"given": {
132+
"foo": [{"a": 1}, {"a": 2}, {"a": 3}],
133+
"bar": [{"a": {"b": 1}}, {"a": {"b": 2}},
134+
{"a": {"b": 3}}]
135+
},
136+
"cases": [
137+
{
138+
"expression": "foo[:2].a",
139+
"result": [1, 2]
140+
},
141+
{
142+
"expression": "foo[:2].b",
143+
"result": []
144+
},
145+
{
146+
"expression": "foo[:2].a.b",
147+
"result": []
148+
},
149+
{
150+
"expression": "bar[::-1].a.b",
151+
"result": [3, 2, 1]
152+
},
153+
{
154+
"expression": "bar[:2].a.b",
155+
"result": [1, 2]
156+
}
157+
]
158+
}, {
159+
"given": [{"a": 1}, {"a": 2}, {"a": 3}],
160+
"cases": [
161+
{
162+
"expression": "[:]",
163+
"result": [{"a": 1}, {"a": 2}, {"a": 3}]
164+
},
165+
{
166+
"expression": "[:2].a",
167+
"result": [1, 2]
168+
},
169+
{
170+
"expression": "[::-1].a",
171+
"result": [3, 2, 1]
172+
},
173+
{
174+
"expression": "[:2].b",
175+
"result": []
176+
}
177+
]
130178
}]

0 commit comments

Comments
 (0)