0
0
GoHow-ToBeginner · 3 min read

How to Unmarshal JSON in Go: Simple Guide with Examples

In Go, you can unmarshal JSON data into a struct or map using the json.Unmarshal function from the encoding/json package. You provide the JSON bytes and a pointer to the variable where you want the data stored, and Go fills it with the matching JSON content.
📐

Syntax

The basic syntax to unmarshal JSON in Go is:

  • json.Unmarshal(data []byte, v interface{}) error takes JSON bytes and a pointer to a variable.
  • data is the JSON input as bytes.
  • v is a pointer to a struct, map, or other data type where JSON will be stored.
  • The function returns an error if JSON is invalid or doesn't match the target type.
go
err := json.Unmarshal(jsonData, &targetVariable)
if err != nil {
    // handle error
}
💻

Example

This example shows how to unmarshal JSON into a Go struct. It reads JSON data representing a person and prints the struct fields.

go
package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    jsonData := []byte(`{"name": "Alice", "age": 30}`)

    var p Person
    err := json.Unmarshal(jsonData, &p)
    if err != nil {
        fmt.Println("Error unmarshaling JSON:", err)
        return
    }

    fmt.Println("Name:", p.Name)
    fmt.Println("Age:", p.Age)
}
Output
Name: Alice Age: 30
⚠️

Common Pitfalls

  • Not passing a pointer to json.Unmarshal causes no data to be filled.
  • JSON field names must match struct tags or field names exactly (case sensitive).
  • Ignoring errors from json.Unmarshal can hide problems.
  • Unmarshaling into incompatible types causes errors.
go
package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    jsonData := []byte(`{"name": "Bob", "age": 25}`)

    var p Person
    // Wrong: passing value instead of pointer
    err := json.Unmarshal(jsonData, p) // This will cause a compile-time error
    if err != nil {
        fmt.Println("Error:", err)
    }
    fmt.Println("Name:", p.Name) // Prints empty string

    // Correct way
    err = json.Unmarshal(jsonData, &p)
    if err != nil {
        fmt.Println("Error:", err)
    }
    fmt.Println("Name:", p.Name) // Prints Bob
}
Output
Name: Name: Bob

Key Takeaways

Always pass a pointer to your variable when using json.Unmarshal.
Use struct tags to match JSON field names with Go struct fields.
Check and handle errors returned by json.Unmarshal.
Unmarshal JSON bytes into structs or maps that match the JSON structure.