【问题标题】:Key name of of marshaled slice of JSON objects needs to be lower case [duplicate]JSON对象的编组切片的键名需要小写[重复]
【发布时间】:2021-11-26 00:52:02
【问题描述】:

如何在此代码的编组 JSON 输出中将密钥名称 Id 设为小写?

    type Topic struct {
        Id string
    }

    topics := []Topic{
        {Id: "some identifier"},
        {Id: "some other identifier"},
    }

    tops, err := json.Marshal(topics)
    if err != nil {
        fmt.Println("got an error", err)
    }

    fmt.Println(string(tops))

返回:

[
    {"Id":"some identifier"},
    {"Id":"some other identifier"}
]

但我使用的 API 需要小写,例如:

[
    {"id":"some identifier"},
    {"id":"some other identifier"}
]

我对 golang 还是很陌生,所以任何方向都值得赞赏!

【问题讨论】:

    标签: json go struct slice


    【解决方案1】:

    你只需设置json struct 标签

    type Topic struct {
        Id string `json:"id"`
    }
    

    【讨论】:

    • 你知道,正如你回答的那样,我突然想到了这个想法,我正要删除这个问题。
    猜你喜欢
    • 2019-06-01
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多