Skip to content

Commit

Permalink
StringMapE support JSON for []byte
Browse files Browse the repository at this point in the history
  • Loading branch information
shockerli committed Jan 5, 2022
1 parent 32ee947 commit 6f83711
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
18 changes: 18 additions & 0 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
Expand Down
5 changes: 4 additions & 1 deletion map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down

0 comments on commit 6f83711

Please sign in to comment.