Languages Knowledge Base

Working with JSON in Go: encoding/json Guide

Complete Go JSON guide: json.Unmarshal, json.Marshal, struct field tags, MarshalIndent for pretty printing, and handling optional fields in Go JSON.

In Go, use json.Unmarshal([]byte(text), &obj) to parse JSON and json.MarshalIndent(obj, "", " ") to produce pretty-printed JSON output using the standard library encoding/json package.

JSON in Go with encoding/json

Go ships with the encoding/json package in the standard library. No external dependency is required.

Struct Field Tags

Use json:"key_name" struct tags to control JSON key names. Use json:"field,omitempty" to omit zero-value fields.

Working with Unknown JSON

Use map[string]interface{} or json.RawMessage for dynamic or partially-known JSON structures.

json
package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    ID       int      `json:"id"`
    Name     string   `json:"name"`
    IsActive bool     `json:"is_active"`
    Roles    []string `json:"roles,omitempty"`
}

func main() {
    // Parse JSON string
    jsonStr := `{"id":1,"name":"Alice","is_active":true,"roles":["admin"]}`
    var user User
    if err := json.Unmarshal([]byte(jsonStr), &user); err != nil {
        panic(err)
    }
    fmt.Println(user.Name) // Alice

    // Serialize to JSON
    jsonBytes, _ := json.Marshal(user)

    // Pretty print
    pretty, _ := json.MarshalIndent(user, "", "  ")
    fmt.Println(string(pretty))
}

Try the free JSON Formatter

Runs entirely in your browser — no upload, no signup, and your data never leaves your device.

Open JSON Formatter

Frequently Asked Questions

How do I pretty print JSON in Go?

Use json.MarshalIndent(obj, "", " ") where the second argument is the prefix and the third is the indent string.

How do I handle optional JSON fields in Go?

Use the omitempty struct tag option: json:"field,omitempty". This omits the field when it has a zero value.

Can I decode JSON into a map in Go?

Yes. Use var m map[string]interface{} and json.Unmarshal(data, &m).

Related JSON Topics & Reference Articles