Go语言将数据反序列化到interface{}后无法访问字段求助
res.Page After JSON Unmarshal to interface{}? Hey there! I see the issue you're running into—let's break this down and fix it step by step.
The Root Cause
When you unmarshal JSON into an interface{} variable, Go automatically converts the JSON data into its corresponding Go primitive types:
- JSON objects become
map[string]interface{} - JSON arrays become
[]interface{} - Numbers become
float64(by default) - Strings stay
string, booleans staybool, etc.
Even though the underlying value of res is a map, its static type is still interface{}. Since interface{} doesn't have a Page field or method, trying to access res.Page directly throws that error.
Fix 1: Use Type Assertion to Access the Underlying Map
You can convert the interface{} to a map[string]interface{} using a type assertion, then access values by their key:
package main import ( "encoding/json" "fmt" ) func main() { var res interface{} str := `{"page": 1, "fruits": ["apple", "peach"]}` err := json.Unmarshal([]byte(str), &res) if err != nil { fmt.Println("Unmarshal error:", err) return } // Assert res is a map[string]interface{} resMap, ok := res.(map[string]interface{}) if !ok { fmt.Println("res is not a map") return } // Access "page" (note it's a float64 by default) page := resMap["page"].(float64) fmt.Println("Page:", page) // Access "fruits" and assert it's a slice fruits := resMap["fruits"].([]interface{}) for _, f := range fruits { fmt.Println("Fruit:", f.(string)) } }
Fix 2: Define a Struct (Recommended)
For type safety and cleaner code, define a struct that matches your JSON structure, then unmarshal directly into it. This way you can access fields directly like res.Page:
package main import ( "encoding/json" "fmt" ) // Define a struct that matches the JSON structure type Response struct { Page int `json:"page"` // JSON key is "page", maps to struct field Page Fruits []string `json:"fruits"` // JSON key "fruits" maps to Fruits } func main() { var res Response str := `{"page": 1, "fruits": ["apple", "peach"]}` err := json.Unmarshal([]byte(str), &res) if err != nil { fmt.Println("Unmarshal error:", err) return } // Now you can access fields directly! fmt.Println("Page:", res.Page) fmt.Println("Fruits:", res.Fruits) }
This approach is better because:
- You get compile-time type checking (no runtime panics if you misspell a field)
- Values are converted to the exact types you want (like
intforPageinstead offloat64) - Code is more readable and maintainable
内容的提问来源于stack exchange,提问作者Test admin

