1
- // Flat flattens a nested Golang map into a one level deep map. Flat also supports unflatten, turn a one level map into nested one.
2
- //
3
- // You can flatten a Go map
4
- //
5
- // in = map[string]interface{}{
6
- // "foo": map[string]interface{}{
7
- // "bar": map[string]interface{}{
8
- // "t": 123,
9
- // },
10
- // "k": 456,
11
- // },
12
- // }
13
- //
14
- // out, err := flat.Flatten(in, nil)
15
- // out = map[string]interface{}{
16
- // "foo.bar.t": 123,
17
- // "foo.k": 456,
18
- // }
19
-
20
- // and a reverse with unflatten
21
- // in = map[string]interface{}{
22
- // "foo.bar.t": 123,
23
- // "foo.k": 456,
24
- // }
25
- // out, err := flat.Unflatten(in, nil)
26
- // out = map[string]interface{}{
27
- // "foo": map[string]interface{}{
28
- // "bar": map[string]interface{}{
29
- // "t": 123,
30
- // },
31
- // "k": 456,
32
- // },
33
- // }
34
-
35
1
package flat
36
2
37
3
import (
@@ -42,20 +8,18 @@ import (
42
8
"github.com/imdario/mergo"
43
9
)
44
10
45
- // Options the flatten options
46
- // by default
47
- // Demiliter: "."
48
- // Safe: false
49
- // MaxDepth: 20
11
+ // Options the flatten options.
12
+ // By default: Demiliter = "."
50
13
type Options struct {
51
14
Delimiter string
52
15
Safe bool
53
- Object bool
54
16
MaxDepth int
55
17
}
56
18
57
19
// Flatten the map, it returns a map one level deep
58
- // regardless of how nested the original map was
20
+ // regardless of how nested the original map was.
21
+ // By default, the flatten has Delimiter = ".", and
22
+ // no limitation of MaxDepth
59
23
func Flatten (nested map [string ]interface {}, opts * Options ) (m map [string ]interface {}, err error ) {
60
24
if opts == nil {
61
25
opts = & Options {
@@ -121,16 +85,11 @@ func flatten(prefix string, depth int, nested interface{}, opts *Options) (flatm
121
85
return
122
86
}
123
87
124
- // merge is the function that update to map with from and key
125
- // example: from is a map
88
+ // update is the function that update to map with from
89
+ // example:
126
90
// to = {"hi": "there"}
127
91
// from = {"foo": "bar"}
128
- // new to = {"hi": "there", "foo": "bar"}
129
- // example: from is an empty map
130
- // to = {"hi": "there"}
131
- // from = {}
132
- // key = "world"
133
- // key = {"hi": "there", "world": {}}
92
+ // then, to = {"hi": "there", "foo": "bar"}
134
93
func update (to map [string ]interface {}, from map [string ]interface {}) {
135
94
for kt , vt := range from {
136
95
to [kt ] = vt
0 commit comments