|
| 1 | +package flatmap |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "reflect" |
| 6 | +) |
| 7 | + |
| 8 | +/* |
| 9 | +Do takes a nested map and flattens it into a single level map. The flattening |
| 10 | +roughly follows the [JSONPath] standard. Please see the example to understand |
| 11 | +how the flattened output looks like. |
| 12 | +
|
| 13 | +[JSONPath]: https://goessner.net/articles/JsonPath/ |
| 14 | +*/ |
| 15 | +func Do(nested map[string]any) map[string]any { |
| 16 | + flattened := map[string]any{} |
| 17 | + for childKey, childValue := range nested { |
| 18 | + setChildren(flattened, childKey, childValue) |
| 19 | + } |
| 20 | + |
| 21 | + return flattened |
| 22 | +} |
| 23 | + |
| 24 | +// setChildren is a helper function for flatten. It is invoked recursively on a |
| 25 | +// child value. If the child is not a map or a slice, then the value is simply |
| 26 | +// set on the flattened map. If the child is a map or a slice, then the |
| 27 | +// function is invoked recursively on the child's values, until a |
| 28 | +// non-map-non-slice value is hit. |
| 29 | +func setChildren(flattened map[string]any, parentKey string, parentValue any) { |
| 30 | + newKey := fmt.Sprintf(".%s", parentKey) |
| 31 | + if reflect.TypeOf(parentValue) == nil { |
| 32 | + flattened[newKey] = parentValue |
| 33 | + return |
| 34 | + } |
| 35 | + |
| 36 | + if reflect.TypeOf(parentValue).Kind() == reflect.Map { |
| 37 | + children := parentValue.(map[string]any) |
| 38 | + for childKey, childValue := range children { |
| 39 | + newKey = fmt.Sprintf("%s.%s", parentKey, childKey) |
| 40 | + setChildren(flattened, newKey, childValue) |
| 41 | + } |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + if reflect.TypeOf(parentValue).Kind() == reflect.Slice { |
| 46 | + children := parentValue.([]any) |
| 47 | + if len(children) == 0 { |
| 48 | + flattened[newKey] = children |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + for childIndex, childValue := range children { |
| 53 | + newKey = fmt.Sprintf("%s[%v]", parentKey, childIndex) |
| 54 | + setChildren(flattened, newKey, childValue) |
| 55 | + } |
| 56 | + return |
| 57 | + } |
| 58 | + |
| 59 | + flattened[newKey] = parentValue |
| 60 | +} |
0 commit comments