-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
108 lines (95 loc) · 2.15 KB
/
main.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"gopkg.in/yaml.v2"
)
func main() {
log.SetFlags(0)
if len(os.Args) > 2 {
fmt.Println("Usage: y2j [file]")
fmt.Println("If file is omitted, then read from stdin.")
os.Exit(2)
}
input := os.Stdin
if len(os.Args) == 2 {
file, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
input = file
}
defer input.Close()
y, err := ioutil.ReadAll(input)
if err != nil {
log.Fatal(err)
}
data := make(map[interface{}]interface{})
err = yaml.Unmarshal(y, &data)
if err != nil {
log.Fatal(err)
}
normalized, err := NormalizeObject(data)
if err != nil {
log.Fatal(err)
}
j, err := json.Marshal(normalized)
if err != nil {
log.Fatal(err)
}
var out bytes.Buffer
json.Compact(&out, j)
out.WriteTo(os.Stdout)
fmt.Println()
}
func NormalizeObject(data map[interface{}]interface{}) (map[string]interface{}, error) {
out := make(map[string]interface{})
for key, value := range data {
stringKey, success := key.(string)
if !success {
return nil, errors.New(fmt.Sprintf("Key was not a string: %v\n", key))
}
if mapValue, success := value.(map[interface{}]interface{}); success {
normalized, err := NormalizeObject(mapValue)
if err != nil {
return nil, err
}
out[stringKey] = normalized
} else if arrayValue, success := value.([]interface{}); success {
normalized, err := NormalizeArray(arrayValue)
if err != nil {
return nil, err
}
out[stringKey] = normalized
} else {
out[stringKey] = value
}
}
return out, nil
}
func NormalizeArray(data []interface{}) ([]interface{}, error) {
out := make([]interface{}, 0, len(data))
for _, value := range data {
if mapValue, success := value.(map[interface{}]interface{}); success {
normalized, err := NormalizeObject(mapValue)
if err != nil {
return nil, err
}
out = append(out, normalized)
} else if arrayValue, success := value.([]interface{}); success {
normalized, err := NormalizeArray(arrayValue)
if err != nil {
return nil, err
}
out = append(out, normalized)
} else {
out = append(out, value)
}
}
return out, nil
}