github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/infra/conf/json/yaml.go (about) 1 package json 2 3 import ( 4 "encoding/json" 5 "fmt" 6 7 "gopkg.in/yaml.v3" 8 ) 9 10 // FromYAML convert yaml to json 11 func FromYAML(v []byte) ([]byte, error) { 12 m1 := make(map[interface{}]interface{}) 13 err := yaml.Unmarshal(v, &m1) 14 if err != nil { 15 return nil, err 16 } 17 m2 := convert(m1) 18 j, err := json.Marshal(m2) 19 if err != nil { 20 return nil, err 21 } 22 return j, nil 23 } 24 25 func convert(m map[interface{}]interface{}) map[string]interface{} { 26 res := map[string]interface{}{} 27 for k, v := range m { 28 var value interface{} 29 switch v2 := v.(type) { 30 case map[interface{}]interface{}: 31 value = convert(v2) 32 case []interface{}: 33 for i, el := range v2 { 34 if m, ok := el.(map[interface{}]interface{}); ok { 35 v2[i] = convert(m) 36 } 37 } 38 value = v2 39 default: 40 value = v 41 } 42 key := "null" 43 if k != nil { 44 key = fmt.Sprint(k) 45 } 46 res[key] = value 47 } 48 return res 49 }