-
Notifications
You must be signed in to change notification settings - Fork 12
/
json.go
65 lines (52 loc) · 1.12 KB
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package config
import (
"encoding/json"
"fmt"
"io/ioutil"
)
type JSONFile struct {
path string
}
func NewJSONFile(path string) *JSONFile {
return &JSONFile{
path: path,
}
}
func (this *JSONFile) Load() (map[string]string, error) {
encodedJSON, err := ioutil.ReadFile(this.path)
if err != nil {
return nil, err
}
decodedJSON := map[string]interface{}{}
if err := json.Unmarshal(encodedJSON, &decodedJSON); err != nil {
return nil, err
}
settings, err := FlattenJSON(decodedJSON, "")
if err != nil {
return nil, err
}
return settings, nil
}
func FlattenJSON(input map[string]interface{}, namespace string) (map[string]string, error) {
flattened := map[string]string{}
for key, value := range input {
var token string
if namespace == "" {
token = key
} else {
token = fmt.Sprintf("%s.%s", namespace, key)
}
if child, ok := value.(map[string]interface{}); ok {
settings, err := FlattenJSON(child, token)
if err != nil {
return nil, err
}
for k, v := range settings {
flattened[k] = v
}
} else {
flattened[token] = fmt.Sprintf("%v", value)
}
}
return flattened, nil
}