Skip to content

Commit

Permalink
feat: add support for camelCase JSON keys
Browse files Browse the repository at this point in the history
  • Loading branch information
alecthomas committed Nov 12, 2022
1 parent 32e8ffc commit d974d72
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
10 changes: 9 additions & 1 deletion resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func (r ResolverFunc) Validate(app *Application) error { return nil } // nolint:

// JSON returns a Resolver that retrieves values from a JSON source.
//
// Hyphens in flag names are replaced with underscores.
// Flag names are used as JSON keys indirectly, by tring snake_case and camelCase variants.
func JSON(r io.Reader) (Resolver, error) {
values := map[string]interface{}{}
err := json.NewDecoder(r).Decode(&values)
Expand All @@ -38,9 +38,12 @@ func JSON(r io.Reader) (Resolver, error) {
}
var f ResolverFunc = func(context *Context, parent *Path, flag *Flag) (interface{}, error) {
name := strings.ReplaceAll(flag.Name, "-", "_")
snakeCaseName := snakeCase(flag.Name)
raw, ok := values[name]
if ok {
return raw, nil
} else if raw, ok = values[snakeCaseName]; ok {
return raw, nil
}
raw = values
for _, part := range strings.Split(name, ".") {
Expand All @@ -58,3 +61,8 @@ func JSON(r io.Reader) (Resolver, error) {

return f, nil
}

func snakeCase(name string) string {
name = strings.Join(strings.Split(strings.Title(name), "-"), "") //nolint: staticcheck
return strings.ToLower(name[:1]) + name[1:]
}
2 changes: 1 addition & 1 deletion resolver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ func TestJSONBasic(t *testing.T) {
"string": "🍕",
"slice": [5, 8],
"bool": true,
"slice_with_commas": ["a,b", "c"],
"sliceWithCommas": ["a,b", "c"],
"one":{
"string": "one value"
},
Expand Down

0 comments on commit d974d72

Please sign in to comment.