Go raises panic: json: cannot unmarshal object into Go struct field error “when you are trying to unmarshal JSON data into a Go struct, and there’s a mismatch between the JSON data and the Go struct definition”.
This can happen for several reasons, such as:
- The Go struct field does not have the same name as the JSON object property.
- The Go struct field is of the wrong type.
- The JSON object property is not present.
To fix the error, follow these steps:
Step 1: Check the JSON data
Ensure the JSON data you are trying to unmarshal is valid and properly formatted. You can use online tools like JSONLint to validate your JSON.
Step 2: Check the Go struct definition
Ensure that the Go struct definition matches the JSON data structure. For example, the struct field names should have the correct JSON tags, and the field types should be compatible with the JSON data types.
{
"name": "Krunal Lathiya",
"age": 30,
"email": "data@example.com"
}
The corresponding Go struct should look like this:
type Student struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email"`
}
Step 3: Unmarshal the JSON data
You can use the json.Unmarshal() function to unmarshal the JSON data into your Go struct.
package main
import (
"encoding/json"
"fmt"
)
type Student struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email"`
}
func main() {
jsonData := []byte(`{
"name": "Krunal Lathiya",
"age": 30,
"email": "data@example.com"
}`)
var student Student
err := json.Unmarshal(jsonData, &student)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Student: %+v\n", student)
}
Output
Student: {Name:Krunal Lathiya Age:30 Email:data@example.com}
Following these steps, you can fix the error.
Conclusion
Here are some tips for avoiding panic: json: cannot unmarshal object into Go struct field error.
- Ensure the Go struct field names match the JSON object property names.
- Ensure the Go struct field types match the JSON object property types.
- Make sure that all required JSON object properties are present.
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.