Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix jsonpath to handle maps with key of nonstring types #23358

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion pkg/util/jsonpath/jsonpath.go
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,13 @@ func (j *JSONPath) evalField(input []reflect.Value, node *FieldNode) ([]reflect.
return nil, err
}
} else if value.Kind() == reflect.Map {
result = value.MapIndex(reflect.ValueOf(node.Value))
mapKeyType := value.Type().Key()
nodeValue := reflect.ValueOf(node.Value)
// node value type must be convertible to map key type
if !nodeValue.Type().ConvertibleTo(mapKeyType) {
return results, fmt.Errorf("%s is not convertible to %s", nodeValue, mapKeyType)
}
result = value.MapIndex(nodeValue.Convert(mapKeyType))
}
if result.IsValid() {
results = append(results, result)
Expand Down
17 changes: 13 additions & 4 deletions pkg/util/jsonpath/jsonpath_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,14 @@ type bicycle struct {
Price float32
}

type empName string
type job string
type store struct {
Book []book
Bicycle bicycle
Name string
Labels map[string]int
Book []book
Bicycle bicycle
Name string
Labels map[string]int
Employees map[empName]job
}

func TestStructInput(t *testing.T) {
Expand All @@ -136,6 +139,10 @@ func TestStructInput(t *testing.T) {
"web/html": 15,
"k8s-app": 20,
},
Employees: map[empName]job{
"jason": "manager",
"dan": "clerk",
},
}

storeTests := []jsonpathTest{
Expand All @@ -147,6 +154,8 @@ func TestStructInput(t *testing.T) {
{"array", "{[0:2]}", []string{"Monday", "Tudesday"}, "Monday Tudesday"},
{"variable", "hello {.Name}", storeData, "hello jsonpath"},
{"dict/", "{$.Labels.web/html}", storeData, "15"},
{"dict/", "{$.Employees.jason}", storeData, "manager"},
{"dict/", "{$.Employees.dan}", storeData, "clerk"},
{"dict-", "{.Labels.k8s-app}", storeData, "20"},
{"nest", "{.Bicycle.Color}", storeData, "red"},
{"allarray", "{.Book[*].Author}", storeData, "Nigel Rees Evelyn Waugh Herman Melville"},
Expand Down
2 changes: 1 addition & 1 deletion pkg/util/jsonpath/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ func (t *TextNode) String() string {
return fmt.Sprintf("%s: %s", t.Type(), t.Text)
}

// FieldNode holds filed of struct
// FieldNode holds field of struct
type FieldNode struct {
NodeType
Value string
Expand Down