How to Fix json: cannot unmarshal object into Go struct field

Diagram of fixing the json - cannot unmarshal object into Go struct field

Panic: json: cannot unmarshal object into Go struct field error occurs in Golang 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:

  1. The Go struct field does not have the same name as the JSON object property.
  2. The Go struct field is of the wrong type.
  3. 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.

Here are some tips for avoiding panic: json: cannot unmarshal object into Go struct field error.

Tip # Description Example & Solution
1 Ensure the Go struct field names match the JSON object property names. If JSON contains: {“Name”:”Krunal”} Go struct should have: Name string OR use tags: json:”Name”
2 Ensure the Go struct field types match the JSON object property types. If JSON contains an integer: {“Age”:30} Go struct should NOT have: Age string Instead, it should have: Age int
3 Make sure that all required JSON object properties are present. If Go struct expects: type Person struct { Name string; Age int } JSON like {“Name”:”Krunal”} without Age might lead to issues if Age is mandatory.

That’s it.