Skip to content

Commit 1f2fa17

Browse files
authored
Merge pull request #10 from superfell/get_key
Optimize map key check in get_key
2 parents 38dc91f + 28480c2 commit 1f2fa17

2 files changed

Lines changed: 22 additions & 0 deletions

File tree

jsonpath.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,16 @@ func get_key(obj interface{}, key string) (interface{}, error) {
283283
}
284284
switch reflect.TypeOf(obj).Kind() {
285285
case reflect.Map:
286+
// if obj came from stdlib json, its highly likely to be a map[string]interface{}
287+
// in which case we can save having to iterate the map keys to work out if the
288+
// key exists
289+
if jsonMap, ok := obj.(map[string]interface{}); ok {
290+
val, exists := jsonMap[key]
291+
if !exists {
292+
return nil, fmt.Errorf("key error: %s not found in object", key)
293+
}
294+
return val, nil
295+
}
286296
for _, kv := range reflect.ValueOf(obj).MapKeys() {
287297
//fmt.Println(kv.String())
288298
if kv.String() == key {

jsonpath_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,18 @@ func init() {
5555
json.Unmarshal([]byte(data), &json_data)
5656
}
5757

58+
func Benchmark_JsonPathLookup(b *testing.B) {
59+
for n := 0; n < b.N; n++ {
60+
res, err := JsonPathLookup(json_data, "$.store.book[0].price")
61+
if res_v, ok := res.(float64); ok != true || res_v != 8.95 {
62+
b.Errorf("$.store.book[0].price should be 8.95")
63+
}
64+
if err != nil {
65+
b.Errorf("Unexpected error: %v", err)
66+
}
67+
}
68+
}
69+
5870
func Test_jsonpath_JsonPathLookup_1(t *testing.T) {
5971
// key from root
6072
res, _ := JsonPathLookup(json_data, "$.expensive")

0 commit comments

Comments
 (0)