Skip to content

Commit

Permalink
fix: map elements of array
Browse files Browse the repository at this point in the history
  • Loading branch information
kevwan committed Dec 7, 2022
1 parent 5ac355f commit fcb8518
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
22 changes: 16 additions & 6 deletions core/conf/config.go
Expand Up @@ -139,15 +139,25 @@ func toCamelCase(s string) string {
return buf.String()
}

func toCamelCaseInterface(v interface{}) interface{} {
switch vv := v.(type) {
case map[string]interface{}:
return toCamelCaseKeyMap(vv)
case []interface{}:
var arr []interface{}
for _, vvv := range vv {
arr = append(arr, toCamelCaseInterface(vvv))
}
return arr
default:
return v
}
}

func toCamelCaseKeyMap(m map[string]interface{}) map[string]interface{} {
res := make(map[string]interface{})
for k, v := range m {
vv, ok := v.(map[string]interface{})
if ok {
res[toCamelCase(k)] = toCamelCaseKeyMap(vv)
} else {
res[toCamelCase(k)] = v
}
res[toCamelCase(k)] = toCamelCaseInterface(v)
}

return res
Expand Down
16 changes: 16 additions & 0 deletions core/conf/config_test.go
Expand Up @@ -56,6 +56,22 @@ func TestConfigJson(t *testing.T) {
}
}

func TestLoadFromJsonBytesArray(t *testing.T) {
input := []byte(`{"users": [{"name": "foo"}, {"Name": "bar"}]}`)
var val struct {
Users []struct {
Name string
}
}

assert.NoError(t, LoadFromJsonBytes(input, &val))
var expect []string
for _, user := range val.Users {
expect = append(expect, user.Name)
}
assert.EqualValues(t, []string{"foo", "bar"}, expect)
}

func TestConfigToml(t *testing.T) {
text := `a = "foo"
b = 1
Expand Down

0 comments on commit fcb8518

Please sign in to comment.