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

Go语言json.Unmarshal报错:指定小写标签仍无法解析?

问题原因分析

你遇到的错误根源在于JSON数据中同时存在两个同名(大小写不同)的键:小写的"length"(数值类型)和大写开头的"Length"(字符串类型),而Go的encoding/json包在解析时,会将这两个键都匹配到结构体的Length字段,最终在处理字符串值时触发类型转换错误。

具体细节:

  • 你的结构体字段Length通过json:"length"标签指定绑定JSON的"length"键,这部分配置是正确的;
  • 但JSON中额外存在的"Length"键,会被encoding/json包匹配到结构体的Length字段(包在解析时,会尝试将JSON键与结构体字段名、json标签进行大小写不敏感的匹配);
  • 当解析到"Length"对应的字符串值"3350"时,系统尝试将其赋值给float64类型的字段,自然会抛出cannot unmarshal string into Go struct field Attributes.length of type float64错误。
解决方法

根据你的场景,可选以下两种方案:

方案1:清理JSON数据

直接删除JSON中多余的"Length"键,只保留小写的"length"数值型键,这样解析就能正常完成。

方案2:新增字段接收字符串键

如果无法修改JSON数据,可以在结构体中新增一个字段来接收"Length"字符串值,避免两个键争夺同一个字段:

type Attributes struct {
    Length    float64 `json:"length"`
    LengthStr string  `json:"Length"` // 新增字段接收字符串类型的Length键
}

验证代码

修改后的代码运行示例:

import (
    "encoding/json"
    "fmt"
)

const fixedData = `{
    "length": 3350,
    "Length": "3350"
}`

type Attributes struct {
    Length    float64 `json:"length"`
    LengthStr string  `json:"Length"`
}

func main() {
    var attributes Attributes
    err := json.Unmarshal([]byte(fixedData), &attributes)
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Println("Length:", attributes.Length)
    fmt.Println("LengthStr:", attributes.LengthStr)
}

运行后将正常输出:

Length: 3350
LengthStr: 3350

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:06:09