0
0
GoHow-ToBeginner · 3 min read

How to Parse JSON Response in Go: Simple Guide

In Go, you parse a JSON response by using the encoding/json package. You define a struct matching the JSON structure and use json.Unmarshal to convert JSON bytes into Go data.
📐

Syntax

To parse JSON in Go, you use the json.Unmarshal function. It takes JSON data as bytes and a pointer to a Go variable where the data will be stored.

  • json.Unmarshal(data []byte, v interface{}) error: Parses JSON data into v.
  • v is usually a pointer to a struct or map matching the JSON format.
go
var jsonData = []byte(`{"name":"Alice","age":30}`)

var person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

err := json.Unmarshal(jsonData, &person)
if err != nil {
    // handle error
}
💻

Example

This example shows how to parse a JSON response string into a Go struct and print the values.

go
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    jsonResponse := `{"name":"Alice","age":30}`

    var person struct {
        Name string `json:"name"`
        Age  int    `json:"age"`
    }

    err := json.Unmarshal([]byte(jsonResponse), &person)
    if err != nil {
        fmt.Println("Error parsing JSON:", err)
        return
    }

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

Common Pitfalls

Common mistakes when parsing JSON in Go include:

  • Not using a pointer when calling json.Unmarshal. It must be a pointer to modify the variable.
  • Struct fields not exported (start with lowercase letter), so JSON cannot fill them.
  • Missing or incorrect JSON tags causing fields not to match JSON keys.
  • Ignoring errors from json.Unmarshal which can hide parsing problems.
go
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    jsonResponse := `{"name":"Alice","age":30}`

    // Wrong: non-pointer
    var person struct {
        Name string `json:"name"`
        Age  int    `json:"age"`
    }

    err := json.Unmarshal([]byte(jsonResponse), person) // missing &
    if err != nil {
        fmt.Println("Error:", err)
    }

    fmt.Println("Name:", person.Name) // Will print empty string

    // Correct way
    err = json.Unmarshal([]byte(jsonResponse), &person)
    if err != nil {
        fmt.Println("Error:", err)
    }

    fmt.Println("Name:", person.Name) // Prints Alice
}
Output
Error: json: Unmarshal(non-pointer main.main.func1 struct { Name string "json:\"name\""; Age int "json:\"age\"" }) Name: Name: Alice
📊

Quick Reference

StepDescription
Import encoding/jsonUse Go's standard package for JSON parsing.
Define structCreate a struct matching JSON keys with exported fields.
Call json.UnmarshalPass JSON bytes and pointer to struct variable.
Check errorAlways handle errors returned by Unmarshal.
Use parsed dataAccess struct fields filled with JSON data.

Key Takeaways

Use encoding/json package and json.Unmarshal to parse JSON in Go.
Always pass a pointer to your struct when unmarshaling JSON.
Struct fields must be exported (start with uppercase) and tagged correctly.
Check and handle errors from json.Unmarshal to catch parsing issues.
Match your struct fields to JSON keys using struct tags for accurate parsing.