go encoding_error ai_generated true

json:无法将字符串解组到类型为 map[string]string 的 Go 结构体字段 Foo.Bar 中

json: cannot unmarshal string into Go struct field Foo.Bar of type map[string]string

ID: go/cannot-unmarshal-string-into-struct-field-of-type-map

其他格式: JSON · Markdown 中文 · English
88%修复率
82%置信度
1证据数
2024-01-10首次发现

版本兼容性

版本状态引入弃用备注
go1.20 active
go1.21 active
go1.22 active

根因分析

JSON 包含字符串值,但 Go 结构体期望映射类型,由于源数据中的 JSON 结构错误或类型不匹配。

English

JSON contains a string value where the Go struct expects a map, due to incorrect JSON structure or type mismatch in the source data.

generic

官方文档

https://pkg.go.dev/encoding/json#Unmarshal

解决方案

  1. Change Go struct field type to string and parse manually: type Foo struct { Bar string } then unmarshal Bar as JSON string into map.
  2. Preprocess JSON to ensure Bar is an object: use json.RawMessage to capture Bar, then check if it's a string and handle accordingly.

无效尝试

常见但无效的做法:

  1. 70% 失败

    Tags only affect naming, not type conversion.

  2. 80% 失败

    UseNumber() only affects number parsing, not type coercion.