-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathyaml2json.go
64 lines (60 loc) · 1.32 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
package yaml2json
import (
"encoding/json"
"fmt"
"strconv"
"gopkg.in/yaml.v2"
)
func Convert(input []byte) ([]byte, error) {
var yamlData interface{}
err := yaml.Unmarshal(input, &yamlData)
if err != nil {
return nil, err
}
jsonData, err := convert(yamlData)
if err != nil {
return nil, err
}
output, err := json.Marshal(jsonData)
if err != nil {
return nil, err
}
return output, nil
}
func convert(inputObj interface{}) (interface{}, error) {
switch inputObj.(type) {
case map[interface{}]interface{}:
input := inputObj.(map[interface{}]interface{})
output := make(map[string]interface{})
for key, value := range input {
var outputKey string
switch key.(type) {
case string:
outputKey = key.(string)
case int:
outputKey = strconv.Itoa(key.(int))
default:
return nil, fmt.Errorf("Expected map key to be a string or int, but was %T", key)
}
outputValue, err := convert(value)
if err != nil {
return nil, err
}
output[outputKey] = outputValue
}
return output, nil
case []interface{}:
input := inputObj.([]interface{})
output := make([]interface{}, len(input))
for i, inputElem := range input {
outputElem, err := convert(inputElem)
if err != nil {
return nil, err
}
output[i] = outputElem
}
return output, nil
default:
return inputObj, nil
}
}