Skip to content

JSON marshaling and unmarshaling in Go

JSON marshaling and unmarshaling in Go refers to the process of converting between in-memory data structures (typically structs or slices) and JSON byte arrays. These operations are fundamental for handling data in APIs, configuration files, and general data interchange^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md].

Go provides the encoding/json package to handle these conversions.^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md] This allows applications to easily serialize data for transmission or storage, and deserialize it when received^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md].

Unmarshaling (Decoding)

Unmarshaling is the process of parsing JSON data (usually as a byte slice) and populating a Go data structure.^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md]

To read JSON from a source like a file or an HTTP request body into a variable, the json.Unmarshal function is used^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md].

fileBytes, err := ioutil.ReadFile("./videos.json")
// ... error handling

var videos []video
err = json.Unmarshal(fileBytes, &videos)
// ... error handling

The function typically takes two arguments: the byte slice containing the JSON data, and a pointer to the target variable where the data should be stored^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md].

Marshaling (Encoding)

Marshaling is the process of converting a Go data structure into a JSON byte slice.^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md]

This is commonly used to prepare data for sending over a network, such as in an HTTP response, or for saving to a file^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md]. The json.Marshal function is used for this purpose^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md].

videoBytes, err := json.Marshal(videos)
// ... error handling

w.Write(videoBytes)

In an HTTP context, the resulting bytes can be written directly to the http.ResponseWriter^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md].

Data Structures

Go uses structs to map data to JSON objects^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md].

type video struct {
    Id          string
    Title       string
    Description string
    Imageurl    string
    Url         string
}

For operations involving multiple items, such as a list of videos, Go uses slices (e.g., []video) to represent JSON arrays^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md].

  • [[Go]]
  • [[HTTP]]
  • [[API]]

Sources

^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md]