JSON in Go

Go: JSON

JSON (JavaScript Object Notation) is a lightweight data format that is easy for humans to read and write and easy for machines to parse and generate. Go provides built-in support for encoding and decoding JSON data using the standard library package encoding/json.

Encode a Go data structure to JSON

To encode a Go data structure to JSON, you can use the json.Marshal() function, which takes a Go value and returns a byte slice containing its JSON representation. For example:


    import (
        "encoding/json"
        "fmt"
    )

    type Person struct {
        Name string
        Age int
    }

    func main() {
        person := Person{Name: "Alice", Age: 30}
        jsonBytes, err := json.Marshal(person)
        if err != nil {
            panic(err)
        }
        fmt.Println(string(jsonBytes)) // Output: {"Name":"Alice","Age":30}
    }

Decode a Go data structure to JSON

To decode JSON data into a Go data structure, you can use the json.Unmarshal() function, which takes a byte slice containing JSON data and a pointer to a Go value, and sets the value to the decoded data.

For example -

    func main() {
        jsonStr := `{"Name":"Bob","Age":25}`
        var person Person
        err := json.Unmarshal([]byte(jsonStr), &person)
        if err != nil {
            panic(err)
        }
        fmt.Println(person.Name, person.Age) // Output: Bob 25
    }

Note that the field names in the Go struct must be exported (i.e. capitalized) in order to be encoded or decoded by the encoding/json package. You can use struct tags to specify custom field names in the JSON data.

For example -

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

    func main() {
        person := Person{Name: "Charlie", Age: 20}
        jsonBytes, err := json.Marshal(person)
        if err != nil {
            panic(err)
        }
        fmt.Println(string(jsonBytes)) // Output: {"name":"Charlie","age":20}
    }