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

Go语言将数据反序列化到interface{}后无法访问字段求助

Why Can't Access 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 stay bool, 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))
 }
}

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 int for Page instead of float64)
  • Code is more readable and maintainable

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:26:04