将yaml转换为不带结构的json [英] Convert yaml to json without struct

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

问题描述

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

我想将此yaml字符串转换为json,因为源数据是动态的,所以我无法将其映射到结构:

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

推荐答案

前言:我优化并改进了以下解决方案,并将其作为库发布在这里: dyno.ConvertMapI2MapS() 使用.

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{}类型进行编组,则

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配置的深度大于一,则此尝试就失败了,因为此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\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)
    }
}

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天全站免登陆