登录
首页 >  Golang >  Go问答

使用 Viper 在 Golang 中对 JSON 字符串进行解析和结构化处理

来源:stackoverflow

时间:2024-03-01 17:06:26 413浏览 收藏

本篇文章给大家分享《使用 Viper 在 Golang 中对 JSON 字符串进行解析和结构化处理》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我从其他地方读取配置,它返回一个映射,所有值都是字符串,并且无法确定 config.mp 映射中的键是什么,所以我想这样做,但是在 unmarshal 后 mp 为零,我怎样才能用好方法做到这一点?钩子什么的?谢谢~

type DB struct {
    Name string   `mapstructure:"name"`
    Ip   string   `mapstructure:"ip"`
    Vars []string `mapstructure:"vars"`
}

type Config struct {
    Aid      string                 `mapstructure:"aid"`
    Times    int                    `mapstructure:"times"`
    Mp       map[string]interface{} `mapstructure:"mp"`
    DBConfig DB                     `mapstructure:"db"`
}

func map2Struct() {

    m := make(map[string]interface{})

    m["aid"] = "123"
    m["db.name"] = "test"
    m["db.ip"] = "10.0.0.2"
    m["db.vars"] = `a, b`
    m["times"] = "1"
    m["mp"] = `{"a": 1, "b": 0.1, "c": "asd", d:[1,2]}`
    v := viper.New()
    v.MergeConfigMap(m)
    v.SetConfigType("properties")

    config := Config{}
    v.Unmarshal(&config)
}


正确答案


在将嵌入式结构与 mapstruct 一起使用时,建议但不必要使用 renamerename

我已重新生成您的场景,如下所示:

type user struct {
    name string   `mapstructure:"name"`
    ip   string   `mapstructure:"ip"`
    vars []string `mapstructure:"vars"`
}

type config struct {
    aid   string                 `mapstructure:"aid"`
    times int                    `mapstructure:"times"`
    mp    map[string]interface{} `mapstructure:"mp"`
    user  `mapstructure:",squash"`
}

func main() {

    input := map[string]interface{}{

        "name":  "test",
        "ip":    "10.0.0.2",
        "vars":  []string{"one", "two", "three"},
        "aid":   "123",
        "times": 12,
        "mp": map[string]interface{}{
            "a": 1,
            "b": 0.1,
            "c": "asd",
            "d": []int{1, 2},
        },
    }

    // convert map to json
    jsonstring, _ := json.marshal(input)
    fmt.println(string(jsonstring))

    // convert json to struct
    s := config{}
    json.unmarshal(jsonstring, &s)
    fmt.println(s)

}

您可以在这里运行它:https://go.dev/play/p/dnoskAmJfry

如果您想使用 viper 则替换:

// convert map to json
    jsonstring, _ := json.marshal(input)
    fmt.println(string(jsonstring))

    // convert json to struct
    s := config{}
    json.unmarshal(jsonstring, &s)
    fmt.println(s)

有了这个:

v := viper.New()
v.MergeConfigMap(input)
v.SetConfigType("properties")

config := Config{}
v.Unmarshal(&config)
fmt.Println(config)

到这里,我们也就讲完了《使用 Viper 在 Golang 中对 JSON 字符串进行解析和结构化处理》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>