Converting YAML to JSON without Predefined Data Structures
Question:
How do you convert a YAML string with a dynamic structure into a JSON string? Unmarshaling into an interface{} results in an unsupported data type (map[interface {}]interface {}).
Answer:
The challenge lies in the unanticipated depth of nested maps and slices when unmarshaling YAML into a generic interface{}. Here's an approach to recursively convert them into map[string]interface{} and []interface{}:
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 }
Example usage:
var body interface{} if err := yaml.Unmarshal([]byte(s), &body); err != nil { panic(err) } body = convert(body) if b, err := json.Marshal(body); err != nil { panic(err) } else { fmt.Printf("Output: %s\n", b) }
Output:
{"Services":[{"Orders":[ {"ID":"$save ID1","SupplierOrderCode":"$SupplierOrderCode"}, {"ID":"$save ID2","SupplierOrderCode":111111}]}]}
Note: This conversion process may result in loss of element order, as Go maps are unordered.
The above is the detailed content of How to Convert a Dynamic YAML String to JSON in Go?. For more information, please follow other related articles on the PHP Chinese website!