github.com/bshelton229/agent@v3.5.4+incompatible/yamltojson/yaml.go (about) 1 package yamltojson 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 8 // This is a fork of gopkg.in/yaml.v2 that fixes anchors with MapSlice 9 "github.com/buildkite/yaml" 10 ) 11 12 func MarshalMapSliceJSON(m yaml.MapSlice) ([]byte, error) { 13 buffer := bytes.NewBufferString("{") 14 length := len(m) 15 count := 0 16 17 for _, item := range m { 18 jsonValue, err := marshalInterfaceJSON(item.Value) 19 if err != nil { 20 return nil, err 21 } 22 buffer.WriteString(fmt.Sprintf("%q:%s", item.Key, string(jsonValue))) 23 count++ 24 if count < length { 25 buffer.WriteString(",") 26 } 27 } 28 29 buffer.WriteString("}") 30 return buffer.Bytes(), nil 31 } 32 33 func marshalSliceJSON(m []interface{}) ([]byte, error) { 34 buffer := bytes.NewBufferString("[") 35 length := len(m) 36 count := 0 37 38 for _, item := range m { 39 jsonValue, err := marshalInterfaceJSON(item) 40 if err != nil { 41 return nil, err 42 } 43 buffer.WriteString(fmt.Sprintf("%s", string(jsonValue))) 44 count++ 45 if count < length { 46 buffer.WriteString(",") 47 } 48 } 49 50 buffer.WriteString("]") 51 return buffer.Bytes(), nil 52 } 53 54 func marshalInterfaceJSON(i interface{}) ([]byte, error) { 55 switch t := i.(type) { 56 case yaml.MapItem: 57 return marshalInterfaceJSON(t.Value) 58 case yaml.MapSlice: 59 return MarshalMapSliceJSON(t) 60 case []yaml.MapItem: 61 var s []interface{} 62 for _, mi := range t { 63 s = append(s, mi.Value) 64 } 65 return marshalSliceJSON(s) 66 case []interface{}: 67 return marshalSliceJSON(t) 68 default: 69 return json.Marshal(i) 70 } 71 }