When working with dynamic data in YAML format, it is often necessary to convert it to JSON for further processing. However, directly unmarshalling YAML into an empty interface{} can result in problems when encountering map[interface{}]interface{} types, as demonstrated in the given scenario.
To address this issue, a recursive function called convert() is employed. This function iterates through the interface{} value and performs the following conversions:
By doing so, the outputted value can be safely marshaled into a JSON string.
Here is an example of how to use the convert() function:
import ( "fmt" "log" "github.com/go-yaml/yaml" "encoding/json" ) func convert(i interface{}) interface{} { switch x := i.(type) { case map[interface{}]interface{}: m2 := map[string]interface{}{} for k, v := range x { m2[k.(string)] = convert(v) } return m2 case []interface{}: for i, v := range x { x[i] = convert(v) } } return i } func main() { // Define the YAML string const s = `Services: - Orders: - ID: $save ID1 SupplierOrderCode: $SupplierOrderCode - ID: $save ID2 SupplierOrderCode: 111111 ` // Unmarshal the YAML string into an empty interface var body interface{} if err := yaml.Unmarshal([]byte(s), &body); err != nil { log.Fatal(err) } // Recursively convert the interface to a map[string]interface{} body = convert(body) // Marshal the converted interface into a JSON string if b, err := json.Marshal(body); err != nil { log.Fatal(err) } else { fmt.Println("Converted JSON:", string(b)) } }
The output of the program is the converted JSON:
Converted JSON: {"Services":[{"Orders":[ {"ID":"$save ID1","SupplierOrderCode":"$SupplierOrderCode"}, {"ID":"$save ID2","SupplierOrderCode":111111}]}]}
The above is the detailed content of How to Safely Convert YAML to JSON in Go Without Losing Data Integrity?. For more information, please follow other related articles on the PHP Chinese website!