在没有结构的情况下将 yaml 转换为 json [英] Convert yaml to json without struct

查看:24
本文介绍了在没有结构的情况下将 yaml 转换为 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Services: 
-   Orders: 
    -   ID: $save ID1
        SupplierOrderCode: $SupplierOrderCode
    -   ID: $save ID2
        SupplierOrderCode: 111111

我想把这个yaml字符串转成json,因为源数据是动态的,所以不能映射到struct:

I want to convert this yaml string to json, cause the source data is dynamic, so I can't map it to a struct:

var body interface{}
err := yaml.Unmarshal([]byte(s), &body)

那我想再把那个接口转成json字符串:

Then I want to convert that interface to json string again:

b, _ := json.Marshal(body)

但是发生错误:

panic: json: unsupported type: map[interface {}]interface {}

推荐答案

前言: 我对以下解决方案进行了优化和改进,并在此处作为库发布:github.com/icza/dyno.下面的 convert() 函数可用作 dyno.转换MapI2MapS().

Foreword: I optimized and improved the below solution, and released it as a library here: github.com/icza/dyno. The below convert() function is available as dyno.ConvertMapI2MapS().

问题在于,如果您使用最通用的 interface{} 类型进行解组,则 github.com/go-yaml/yaml 解组键值对的包将是 map[interface{}]interface{}.

The problem is that if you use the most generic interface{} type to unmarshal into, the default type used by the github.com/go-yaml/yaml package to unmarshal key-value pairs will be map[interface{}]interface{}.

第一个想法是使用 map[string]interface{}:

var body map[string]interface{}

但是,如果 yaml 配置的深度超过 1,则此尝试会失败,因为此 body 映射将包含其他映射,其类型将再次为 map[interface{}]interface{}.

But this attempt falls short if the depth of the yaml config is more than one, as this body map will contain additional maps whose type will again be map[interface{}]interface{}.

问题是深度未知,可能还有地图以外的其他值,所以使用map[string]map[string]interface{}不好.

The problem is that the depth is unknown, and there may be other values than maps, so using map[string]map[string]interface{} is not good.

一种可行的方法是让 yaml 解组为 interface{} 类型的值,并递归地遍历结果,然后转换每个遇到的 map[interface{}]interface{} 到一个 map[string]interface{} 值.地图和切片都必须处理.

A viable approach is to let yaml unmarshal into a value of type interface{}, and go through the result recursively, and convert each encountered map[interface{}]interface{} to a map[string]interface{} value. Both maps and slices have to be handled.

下面是这个转换器函数的一个例子:

Here's an example of this converter function:

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() {
    fmt.Printf("Input: %s
", 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
", b)
    }
}

const s = `Services:
-   Orders:
    -   ID: $save ID1
        SupplierOrderCode: $SupplierOrderCode
    -   ID: $save ID2
        SupplierOrderCode: 111111
`

输出:

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}]}]}

需要注意的一点:通过 Go 映射从 yaml 切换到 JSON,您将丢失项目的顺序,因为 Go 映射中的元素(键值对)没有排序.这可能是也可能不是问题.

One thing to note: by switching from yaml to JSON via Go maps you'll lose the order of the items, as elements (key-value pairs) in a Go map are not ordered. This may or may not be a problem.

这篇关于在没有结构的情况下将 yaml 转换为 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆