github.com/viant/toolbox@v0.34.5/yaml.go (about) 1 package toolbox 2 3 import ( 4 "bytes" 5 "fmt" 6 "gopkg.in/yaml.v2" 7 ) 8 9 //AsYamlText converts data structure int text YAML 10 func AsYamlText(source interface{}) (string, error) { 11 if IsStruct(source) || IsMap(source) || IsSlice(source) { 12 buf := new(bytes.Buffer) 13 err := yaml.NewEncoder(buf).Encode(source) 14 return buf.String(), err 15 } 16 return "", fmt.Errorf("unsupported type: %T", source) 17 } 18 19 //NormalizeKVPairs converts slice of KV paris into a map, and map[interface{}]interface{} to map[string]interface{} 20 func NormalizeKVPairs(source interface{}) (interface{}, error) { 21 if source == nil { 22 return source, nil 23 } 24 isDataStruct := IsMap(source) || IsStruct(source) || IsSlice(source) 25 var err error 26 var normalized interface{} 27 if isDataStruct { 28 var aMap = make(map[string]interface{}) 29 30 err = ProcessMap(source, func(k, value interface{}) bool { 31 var key = AsString(k) 32 aMap[key] = value 33 if value == nil { 34 return true 35 } 36 if IsMap(value) || IsSlice(value) || IsStruct(value) { 37 if normalized, err = NormalizeKVPairs(value); err == nil { 38 aMap[key] = normalized 39 } 40 } 41 return true 42 }) 43 if err == nil { 44 return aMap, nil 45 } 46 if IsSlice(aMap) { 47 return source, err 48 } 49 if IsSlice(source) { //yaml style map conversion if applicable 50 aSlice := AsSlice(source) 51 if len(aSlice) == 0 { 52 return source, nil 53 } 54 for i, item := range aSlice { 55 if item == nil { 56 continue 57 } 58 if IsMap(item) || IsSlice(item) { 59 if normalized, err = NormalizeKVPairs(item); err == nil { 60 aSlice[i] = normalized 61 } else { 62 return source, nil 63 } 64 } 65 } 66 return aSlice, nil 67 } 68 } 69 return source, err 70 }