You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言json.Marshal序列化时如何将键名Id修改为小写id

解决方案

Go标准库encoding/json序列化结构体时,默认会以导出字段(首字母大写的字段)的名称作为JSON的键,你可以通过给结构体字段添加json标签自定义序列化后的键名,调整后的代码如下:

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

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

常用json标签扩展说明

  • 若需要字段为空值时自动在序列化结果中忽略该字段,可添加omitempty参数:`json:"id,omitempty"`
  • 若需要某个导出字段完全不参与JSON序列化,可将标签设置为:`json:"-"`
  • 注意标签的包裹符号是英文反引号,不要使用单引号或双引号

内容的提问来源于stack exchange,提问作者Dshiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:18:03