-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathyaml2json.go
66 lines (60 loc) · 2.04 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
//==============================================================================
//
// drone-gdm/yaml2json.go: JSON marshalling overrides to facilitate easy
// conversion of yaml data to json.
//
// Copyright (c) 2017 The New York Times Company
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this library except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//------------------------------------------------------------------------------
package plugin
import (
"encoding/json"
"fmt"
)
// Encode an object into JSON which may have initially been non-compliant due
// to non-string keys in the top-level or nested objects.
func Y2JMarshal(i interface{}) ([]byte, error) {
return json.Marshal(y2jConvert(i))
}
// Take an input interface which may have been populated by YAML decoder (i.e.
// a structure which may contain non-string keys or have nested objects with
// non-string keys) and return a clone of the object with the key types updated
// to be JSON compliant.
func y2jConvert(i interface{}) interface{} {
switch i.(type) {
case map[interface{}]interface{}:
return y2jMap(i)
case []interface{}:
return y2jList(i)
default:
return i
}
}
// Convert YAML maps to JSON maps
func y2jMap(yMap interface{}) interface{} {
jMap := make(map[string](interface{}))
for k, v := range yMap.(map[interface{}]interface{}) {
jMap[fmt.Sprintf("%v", k)] = y2jConvert(v)
}
return jMap
}
// Convert YAML lists to JSON lists
func y2jList(yList interface{}) interface{} {
var jList []interface{}
for _, i := range yList.([]interface{}) {
jList = append(jList, y2jConvert(i))
}
return jList
}