Home > Backend Development > Golang > How to Convert a Dynamic YAML String to JSON in Go?

How to Convert a Dynamic YAML String to JSON in Go?

Mary-Kate Olsen
Release: 2024-12-10 04:11:20
Original
777 people have browsed it

How to Convert a Dynamic YAML String to JSON in Go?

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
}
Copy after login

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)
}
Copy after login

Output:

{"Services":[{"Orders":[
    {"ID":"$save ID1","SupplierOrderCode":"$SupplierOrderCode"},
    {"ID":"$save ID2","SupplierOrderCode":111111}]}]}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template