Home > Backend Development > Golang > How to Safely Convert YAML to JSON in Go Without Losing Data Integrity?

How to Safely Convert YAML to JSON in Go Without Losing Data Integrity?

Barbara Streisand
Release: 2024-12-01 18:02:12
Original
244 people have browsed it

How to Safely Convert YAML to JSON in Go Without Losing Data Integrity?

Converting YAML to JSON Without Struct Binding

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.

Solution: Recursive Type Conversion

To address this issue, a recursive function called convert() is employed. This function iterates through the interface{} value and performs the following conversions:

  • Converts map[interface{}]interface{} values to map[string]interface{}.
  • Converts []interface{} values to []interface{}.

By doing so, the outputted value can be safely marshaled into a JSON string.

Example

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

Output

The output of the program is the converted JSON:

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

Notes

  • By converting to Go maps, the order of elements is lost, so it may not be suitable for scenarios where order is important.
  • An optimized and improved version of the convert() function has been released as a library at github.com/icza/dyno. It offers convenience and flexibility for handling dynamic YAML data.

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!

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