go encoding_error ai_generated true

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

Also available as: JSON · Markdown · 中文
88%Fix Rate
82%Confidence
1Evidence
2024-01-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
go1.20 active
go1.21 active
go1.22 active

Root Cause

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

中文

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

Official Documentation

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

Workarounds

  1. 90% success Change Go struct field type to string and parse manually: type Foo struct { Bar string } then unmarshal Bar as JSON string into map.
    Change Go struct field type to string and parse manually: type Foo struct { Bar string } then unmarshal Bar as JSON string into map.
  2. 85% success Preprocess JSON to ensure Bar is an object: use json.RawMessage to capture Bar, then check if it's a string and handle accordingly.
    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. 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.

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Tags only affect naming, not type conversion.

  2. 80% fail

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