feat(ToStringMapStringE): Add support for non string JOSN value

This commit is contained in:
Baodong 2020-10-10 11:41:53 +08:00
parent 8d17101741
commit 4b1e5dfe94
3 changed files with 10 additions and 2 deletions

View File

@ -907,6 +907,8 @@ func TestToStringMapStringE(t *testing.T) {
var jsonString = `{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}`
var invalidJsonString = `{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"`
var emptyString = ""
var jsonStringWithNonString = `{"key 1": "100", "key 2": -200, "key 3": 3.1415926}`
var mapStringWithNonString = map[string]string{"key 1": "100", "key 2": "-200", "key 3": "3.1415926"}
tests := []struct {
input interface{}
@ -918,6 +920,7 @@ func TestToStringMapStringE(t *testing.T) {
{interfaceMapString, stringMapString, false},
{interfaceMapInterface, stringMapString, false},
{jsonString, stringMapString, false},
{jsonStringWithNonString, mapStringWithNonString, false},
// errors
{nil, nil, true},

View File

@ -874,8 +874,11 @@ func ToStringMapStringE(i interface{}) (map[string]string, error) {
}
return m, nil
case string:
err := jsonStringToObject(v, &m)
return m, err
var temp = map[string]interface{}{}
if err := jsonStringToObject(v, &temp); err != nil {
return nil, err
}
return ToStringMapStringE(temp)
default:
return m, fmt.Errorf("unable to cast %#v of type %T to map[string]string", i, i)
}

2
go.mod
View File

@ -1,5 +1,7 @@
module github.com/spf13/cast
go 1.15
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect