go type_error ai_generated true

json: 无法将数组反序列化为结构体类型 struct { Name string }

json: cannot unmarshal array into Go value of type struct { Name string }

ID: go/json-cannot-unmarshal-array-into-struct

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-03-05首次发现

版本兼容性

版本状态引入弃用备注
1.21 active

根因分析

JSON 数据是数组,但目标 Go 类型是结构体,导致类型不匹配。

English

JSON data is an array but target Go type is a struct, causing type mismatch.

generic

解决方案

  1. 95% 成功率
    Unmarshal into []struct{ Name string } if JSON is array: var data []struct{Name string}; json.Unmarshal([]byte(jsonStr), &data)
  2. 85% 成功率
    Use json.RawMessage to inspect first, then unmarshal accordingly.

无效尝试

常见但无效的做法:

  1. 90% 失败

    Data not parsed, leads to nil values.

  2. 40% 失败

    May not match API contract; breaks other code.