forked from bronze1man/yaml2json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
76 lines (70 loc) · 1.27 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
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
goyaml "gopkg.in/yaml.v2"
)
func main() {
err := translate(os.Stdin, os.Stdout)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
os.Exit(0)
}
func translate(in io.Reader, out io.Writer) error {
input, err := ioutil.ReadAll(in)
if err != nil {
return err
}
var data interface{}
err = goyaml.Unmarshal(input, &data)
if err != nil {
return err
}
input = nil
err = transformData(&data)
if err != nil {
return err
}
output, err := json.Marshal(data)
if err != nil {
return err
}
data = nil
_, err = out.Write(output)
return err
}
func transformData(pIn *interface{}) (err error) {
switch in := (*pIn).(type) {
case map[interface{}]interface{}:
m := make(map[string]interface{}, len(in))
for k, v := range in {
if err = transformData(&v); err != nil {
return err
}
var sk string
switch k.(type) {
case string:
sk = k.(string)
case int:
sk = strconv.Itoa(k.(int))
default:
return fmt.Errorf("type mismatch: expect map key string or int; got: %T", k)
}
m[sk] = v
}
*pIn = m
case []interface{}:
for i := len(in) - 1; i >= 0; i-- {
if err = transformData(&in[i]); err != nil {
return err
}
}
}
return nil
}