From 6f83711ba8bf392390115730af401818619a7c9d Mon Sep 17 00:00:00 2001 From: shockerli Date: Wed, 5 Jan 2022 15:06:05 +0800 Subject: [PATCH] `StringMapE` support JSON for []byte --- map.go | 18 ++++++++++++++++++ map_test.go | 5 ++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/map.go b/map.go index 1eafb81..2e647b2 100644 --- a/map.go +++ b/map.go @@ -15,6 +15,19 @@ func StringMapE(val interface{}) (m map[string]interface{}, err error) { return nil, errUnsupportedTypeNil } + // direct type(for improve performance) + switch v := val.(type) { + case map[string]interface{}: + return v, nil + case []byte: + err = json.Unmarshal(v, &m) + return + case string: + err = json.Unmarshal([]byte(v), &m) + return + } + + // indirect type _, rv := indirect(val) switch rv.Kind() { case reflect.Map: @@ -23,6 +36,11 @@ func StringMapE(val interface{}) (m map[string]interface{}, err error) { } case reflect.Struct: m = struct2map(rv) + case reflect.Slice: + // []byte + if rv.Type().Elem().Kind() == reflect.Uint8 { + err = json.Unmarshal(rv.Bytes(), &m) + } case reflect.String: // JSON string of map err = json.Unmarshal([]byte(rv.String()), &m) diff --git a/map_test.go b/map_test.go index 2e669dc..c0f470f 100644 --- a/map_test.go +++ b/map_test.go @@ -12,10 +12,13 @@ func TestStringMapE(t *testing.T) { expect map[string]interface{} isErr bool }{ - // JSON String + // JSON {`{"name":"cvt","age":3.21}`, map[string]interface{}{"name": "cvt", "age": 3.21}, false}, {`{"name":"cvt","tag":"convert"}`, map[string]interface{}{"name": "cvt", "tag": "convert"}, false}, {`{"name":"cvt","build":true}`, map[string]interface{}{"name": "cvt", "build": true}, false}, + {[]byte(`{"name":"cvt","build":true}`), map[string]interface{}{"name": "cvt", "build": true}, false}, + {AliasTypeString(`{"name":"cvt","build":true}`), map[string]interface{}{"name": "cvt", "build": true}, false}, + {AliasTypeBytes(`{"name":"cvt","build":true}`), map[string]interface{}{"name": "cvt", "build": true}, false}, // Map {map[string]interface{}{}, map[string]interface{}{}, false},