Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add option to use brackets for array indexes #18

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions flatten.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ type SeparatorStyle struct {
Before string // Prepend to key
Middle string // Add between keys
After string // Append to key

UseBracketsForArrayIndex bool
}

// Default styles
Expand Down Expand Up @@ -102,12 +104,12 @@ func flatten(top bool, flatMap map[string]interface{}, nested interface{}, prefi
switch nested.(type) {
case map[string]interface{}:
for k, v := range nested.(map[string]interface{}) {
newKey := enkey(top, prefix, k, style)
newKey := enkey(top, false, prefix, k, style)
assign(newKey, v)
}
case []interface{}:
for i, v := range nested.([]interface{}) {
newKey := enkey(top, prefix, strconv.Itoa(i), style)
newKey := enkey(top, true, prefix, strconv.Itoa(i), style)
assign(newKey, v)
}
default:
Expand All @@ -117,13 +119,17 @@ func flatten(top bool, flatMap map[string]interface{}, nested interface{}, prefi
return nil
}

func enkey(top bool, prefix, subkey string, style SeparatorStyle) string {
func enkey(top, arrayIndex bool, prefix, subkey string, style SeparatorStyle) string {
key := prefix

if top {
key += subkey
} else {
key += style.Before + style.Middle + subkey + style.After
if arrayIndex && style.UseBracketsForArrayIndex {
key += "[" + subkey + "]"
} else {
key += style.Before + style.Middle + subkey + style.After
}
}

return key
Expand Down
22 changes: 22 additions & 0 deletions flatten_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,28 @@ func TestFlattenString(t *testing.T) {
DotStyle,
nil,
},
// 14 -- json path style
{
`{ "a": { "b" : { "array" : [ "d" , "e" ] } }, "number": 1.4567,"bool": true }`,
`{ "flag-a.b.array[0]":"d","flag-a.b.array[1]": "e","flag-bool": true,"flag-number": 1.4567 }`,
"flag-",
SeparatorStyle{
Middle: ".",
UseBracketsForArrayIndex: true,
},
nil,
},
// 14 -- json path style with array of objects
{
`{ "a": { "b" : { "array" : [ { "d" : "e" } ] } }, "number": 1.4567,"bool": true }`,
`{ "flag-a.b.array[0].d": "e","flag-bool": true,"flag-number": 1.4567 }`,
"flag-",
SeparatorStyle{
Middle: ".",
UseBracketsForArrayIndex: true,
},
nil,
},
}

for i, test := range cases {
Expand Down