Marshalling &Unmarshalling JSON with Golang

Okan Özşahin
3 min readOct 12, 2023

--

Marshalling and unmarshalling are often used when dealing with HTTP requests in Go. You typically marshal data to send it in an HTTP request and unmarshal data received in an HTTP response. JSON is a common format for this purpose.

Here’s how you can marshal and unmarshal data in the context of an HTTP request in Go:

Marshalling (Sending Data in an HTTP Request)

When you want to send data in an HTTP request, you can marshal a Go struct or any data into JSON and include it in the request body. Here’s an example:

package main

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)

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

func main() {
person := Person{
Name: "Alice",
Age: 25,
}

// Marshal the struct to JSON
jsonData, err := json.Marshal(person)
if err != nil {
fmt.Println("Error marshalling JSON:", err)
return
}

// Create an HTTP POST request with the JSON data
url := "https://example.com/api/endpoint"
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Println("Error creating request:", err)
return
}

req.Header.Set("Content-Type", "application/json")

// Send the HTTP request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()

// Process the response if needed
// ...
}

Unmarshalling (Handling HTTP Response)

When you receive an HTTP response containing JSON data, you can unmarshal it into a Go struct or any data structure for further processing. Here’s an example:

package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)

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

func main() {
url := "https://example.com/api/endpoint"
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error sending GET request:", err)
return
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
fmt.Println("Request failed with status code:", resp.StatusCode)
return
}

// Read and unmarshal the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return
}

var person Person
err = json.Unmarshal(body, &person)
if err != nil {
fmt.Println("Error unmarshalling JSON:", err)
return
}

fmt.Println("Name:", person.Name)
fmt.Println("Age:", person.Age)
}

In this example, we send an HTTP GET request and unmarshal the JSON response body into a Person struct for further processing. These examples demonstrate how to marshal and unmarshal data when working with HTTP requests and responses in Go using JSON as the encoding format. You can adapt these principles to work with other formats like XML or custom binary formats by using the corresponding encoding and decoding libraries.

Why do we need to Marshall and Unmarshall?

Marshalling is the process of converting a complex data structure (like a Go struct) into a format that can be easily transmitted or stored, such as JSON or XML. Marshalling enables you to represent complex data in a structured and standardized way that can be shared across different platforms and systems. Unmarshalling is the reverse process of marshalling. It allows you to take data in a serialized format (e.g., JSON) and convert it back into a native data structure in your programming language. This is crucial for interpreting and using data received from external sources, such as APIs or files.

In the context of network communication, such as RESTful APIs, HTTP requests, or RPC (Remote Procedure Call), marshalling allows you to send data from one system to another. Unmarshalling is used on the receiving end to extract and interpret the data. Different systems and programming languages may have different data representation formats. Marshalling data into a common format (like JSON) enables inter-operability between these systems. It allows systems written in different languages to communicate effectively by sharing data in a standardized format.

When you need to save data to a database or a file, you often marshal it into a suitable format (e.g., JSON or XML) for storage. Later, when you retrieve the data, you unmarshal it to recreate the original data structure.

During unmarshalling, you can validate and sanitize incoming data to ensure it meets your application’s requirements and security standards. This helps protect your application from malicious or poorly formatted data.

--

--

Okan Özşahin

Backend Developer at hop | Civil Engineer | MS Computer Engineering