Skip to content
Go

JSON Encoding/Decoding

Convert between structs and JSON.

By EZ4Code Team
jsonserialize

Code

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email,omitempty"`
    Age   int    `json:"-"` // Ignore
}

func main() {
    u := User{ID: 1, Name: "Alice", Email: "[email protected]"}

    // Encode
    data, _ := json.Marshal(u)
    fmt.Println(string(data))

    // Decode
    var u2 User
    json.Unmarshal([]byte(`{"id":2,"name":"Bob"}`), &u2)
    fmt.Println(u2)

    // Streaming encode/decode
    json.NewEncoder(os.Stdout).Encode(u)
}

Explanation

Control JSON field names and omitempty behavior via struct tags.

More Go Snippets