jsondecode.com logo

JSON in Go — Marshal, Unmarshal & Struct Tags

Go's encoding/json package is part of the standard library. JSON is marshalled to/from Go structs using struct tags that control field names.

Unmarshal JSON into a struct

Define a struct with json tags matching the JSON keys. Use json.Unmarshal() to parse.

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

func main() {
    data := []byte(`{"id":1,"name":"Alice","email":"alice@example.com"}`)
    var user User
    if err := json.Unmarshal(data, &user); err != nil {
        panic(err)
    }
    fmt.Println(user.Name) // Alice
}

Marshal a struct to JSON

Use json.Marshal() to encode a Go struct to JSON bytes, or json.MarshalIndent() for pretty-printing.

user := User{ID: 1, Name: "Alice", Email: "alice@example.com"}

// Compact
b, err := json.Marshal(user)
fmt.Println(string(b))

// Pretty
b, err = json.MarshalIndent(user, "", "  ")
fmt.Println(string(b))

Omit empty fields

Add omitempty to the json tag to skip zero-value fields during marshalling.

type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email,omitempty"` // omitted if empty
}

Dynamic JSON with map

Use map[string]interface{} when the JSON structure is not known at compile time.

var result map[string]interface{}
if err := json.Unmarshal(data, &result); err != nil {
    panic(err)
}

name := result["name"].(string)
fmt.Println(name)

Format and validate your JSON instantly

Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.

Open JSON Formatter →