Skip to content

Commit

Permalink
Non string map keys (#186)
Browse files Browse the repository at this point in the history
* Fix non-string map keys bug

* Release notes
  • Loading branch information
ohler55 authored Sep 15, 2024
1 parent e422fbd commit 0844e7e
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 16 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

The structure and content of this file follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

## [1.24.1] - 2024-09-15
### Fixed
- Fixed reflection map key matches when keys are string derivitives.

## [1.24.0] - 2024-08-09
### Added
- Added the `jp.PathMatch` function that compares a normalized JSONPath with a target JSONPath.
Expand Down
7 changes: 6 additions & 1 deletion jp/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -1654,7 +1654,12 @@ func (x Expr) reflectGetChild(data any, key string) (v any, has bool) {
has = true
}
case reflect.Map:
rv := rd.MapIndex(reflect.ValueOf(key))
mkt := rt.Key()
kt := reflect.TypeOf(key)
if !kt.ConvertibleTo(mkt) {
break
}
rv := rd.MapIndex(reflect.ValueOf(key).Convert(mkt))
if rv.IsValid() && rv.CanInterface() {
v = rv.Interface()
has = true
Expand Down
31 changes: 16 additions & 15 deletions jp/get_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1381,18 +1381,19 @@ func TestGetMultiFilter(t *testing.T) {
tt.Equal(t, "{c: 1}", pretty.SEN(x.First(data)))
}

// func TestGetDev(t *testing.T) {
// data := map[string]any{
// "a": []any{
// map[string]any{
// "b": []any{
// map[string]any{"c": 1},
// map[string]any{"c": 2},
// map[string]any{"c": 3},
// },
// },
// },
// }
// x := jp.MustParseString("a[?(@.b[*].c == 2)]")
// fmt.Printf("*** result: %s\n", pretty.SEN(x.Get(data)))
// }
type Key string
type X struct {
Y Key
}

func TestGetNonStringKey(t *testing.T) {
data := map[Key]*X{Key("a"): {Y: Key("xyz")}}
x := jp.MustParseString("$.a.y")
tt.Equal(t, "[xyz]", pretty.SEN(x.Get(data)))
}

func TestGetKeyMismatch(t *testing.T) {
data := map[int]*X{1: {Y: Key("xyz")}}
x := jp.MustParseString("$.a.y")
tt.Equal(t, "[]", pretty.SEN(x.Get(data)))
}

0 comments on commit 0844e7e

Please sign in to comment.