-
Notifications
You must be signed in to change notification settings - Fork 6
/
yaml2json.go
80 lines (72 loc) · 1.41 KB
/
yaml2json.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
package main
import (
"bytes"
"encoding/json"
"gopkg.in/yaml.v2"
"log"
"strconv"
"text/template"
)
func transformData(in interface{}) (out interface{}, err error) {
switch in.(type) {
case map[interface{}]interface{}:
o := make(map[string]interface{})
for k, v := range in.(map[interface{}]interface{}) {
sk := ""
switch k.(type) {
case string:
sk = k.(string)
case int:
sk = strconv.Itoa(k.(int))
default:
log.Fatal(err)
}
v, err = transformData(v)
if err != nil {
return nil, err
}
o[sk] = v
}
return o, nil
case []interface{}:
in1 := in.([]interface{})
len1 := len(in1)
o := make([]interface{}, len1)
for i := 0; i < len1; i++ {
o[i], err = transformData(in1[i])
if err != nil {
return nil, err
}
}
return o, nil
default:
return in, nil
}
return in, nil
}
func yaml2Json(file []byte, tag string) []byte {
var data interface{}
t := template.New("artifact")
t, _ = t.Parse(string(file))
yamdata := new(bytes.Buffer)
ddata := DroneData{TAG: tag}
t.Execute(yamdata, ddata)
err := yaml.Unmarshal(yamdata.Bytes(), &data)
data, err = transformData(data)
if err != nil {
log.Fatal(err)
}
file, err = json.Marshal(data)
if err != nil {
log.Fatal(err)
}
if string(file) != "null" {
return file
} else {
return nil
}
}
func isJSON(s string) bool {
var js map[string]interface{}
return json.Unmarshal([]byte(s), &js) == nil
}