Skip to content

Commit a3f42c9

Browse files
Merge pull request #96201 from brianpursley/automated-cherry-pick-of-#95933-upstream-release-1.19
Automated cherry pick of #95933: Fix bug in JSON path parser where an error occurs when a Kubernetes-commit: c902abad10b9c58ca0cddf36e01aa20d30961ffa
2 parents 4fcdf7e + 377de3d commit a3f42c9

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

util/jsonpath/jsonpath.go

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,13 +103,23 @@ func (j *JSONPath) FindResults(data interface{}) ([][]reflect.Value, error) {
103103
if j.beginRange > 0 {
104104
j.beginRange--
105105
j.inRange++
106-
for _, value := range results {
106+
if len(results) > 0 {
107+
for _, value := range results {
108+
j.parser.Root.Nodes = nodes[i+1:]
109+
nextResults, err := j.FindResults(value.Interface())
110+
if err != nil {
111+
return nil, err
112+
}
113+
fullResult = append(fullResult, nextResults...)
114+
}
115+
} else {
116+
// If the range has no results, we still need to process the nodes within the range
117+
// so the position will advance to the end node
107118
j.parser.Root.Nodes = nodes[i+1:]
108-
nextResults, err := j.FindResults(value.Interface())
119+
_, err := j.FindResults(nil)
109120
if err != nil {
110121
return nil, err
111122
}
112-
fullResult = append(fullResult, nextResults...)
113123
}
114124
j.inRange--
115125

util/jsonpath/jsonpath_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,21 @@ func TestKubernetes(t *testing.T) {
393393
testJSONPathSortOutput(randomPrintOrderTests, t)
394394
}
395395

396+
func TestEmptyRange(t *testing.T) {
397+
var input = []byte(`{"items":[]}`)
398+
var emptyList interface{}
399+
err := json.Unmarshal(input, &emptyList)
400+
if err != nil {
401+
t.Error(err)
402+
}
403+
404+
tests := []jsonpathTest{
405+
{"empty range", `{range .items[*]}{.metadata.name}{end}`, &emptyList, "", false},
406+
{"empty nested range", `{range .items[*]}{.metadata.name}{":"}{range @.spec.containers[*]}{.name}{","}{end}{"+"}{end}`, &emptyList, "", false},
407+
}
408+
testJSONPath(tests, true, t)
409+
}
410+
396411
func TestNestedRanges(t *testing.T) {
397412
var input = []byte(`{
398413
"items": [

0 commit comments

Comments
 (0)