YAML to JSON Conversion for Dynamic Data without Structs
When dealing with dynamic data that cannot be mapped to a struct, converting YAML to JSON can pose challenges. Consider the following YAML string:
Services: - Orders: - ID: $save ID1 SupplierOrderCode: $SupplierOrderCode - ID: $save ID2 SupplierOrderCode: 111111
To convert this YAML string to JSON, one approach is to unmarshal it into an interface{} type. However, this results in unsupported types, as the default type used to unmarshal key-value pairs is map[interface{}]interface{}.
To overcome this issue, we need to convert the map[interface{}]interface{} values to map[string]interface{} values recursively. Here's a function that performs this conversion:
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 }
Using this function, we can convert the YAML string to JSON as follows:
import ( "encoding/json" "fmt" "github.com/go-yaml/yaml" ) const s = `Services: - Orders: - ID: $save ID1 SupplierOrderCode: $SupplierOrderCode - ID: $save ID2 SupplierOrderCode: 111111 ` func main() { fmt.Printf("Input: %s\n", s) 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:
Input: Services: - Orders: - ID: $save ID1 SupplierOrderCode: $SupplierOrderCode - ID: $save ID2 SupplierOrderCode: 111111 Output: {"Services":[{"Orders":[ {"ID":"$save ID1","SupplierOrderCode":"$SupplierOrderCode"}, {"ID":"$save ID2","SupplierOrderCode":111111}]}]}
The above is the detailed content of How to Efficiently Convert YAML to JSON with Dynamic Data and No Structs?. For more information, please follow other related articles on the PHP Chinese website!