Development

How To Convert A Struct to JSON in Go

In this tutorial we will guide you on how to convert a Struct to JSON in Go with easy-to-understand examples.
Captain Salem 3 min read
How To Convert A Struct to JSON in Go

Go has built-in packages that make it easy to encode and decode JSON data.

Prerequisites:

  1. The Go Compiler installed on your machine.
  2. A basic understanding of Go syntax and structures.

You can learn how to install Go on your system using the tutorials:

How to install Golang on macOS
A short tutorial with instructions on how to install and setup the Go compiler on macOS.
How to install Golang on Linux
In this tutorial, you will learn how to install and configure the Go compiler on your Linux machine.

Import the Required Packages

The first steps is to import the required packages. In this tutorial, we will use the fmt and encoding/json packages which we can import with the following statement.

package main
import (
	"encoding/json"
	"fmt"
)
...

The encoding/json package provides functions to work with JSON data.

Defining Go Struct

The next step is to define the struct that we wish to convert to JSON. In the example, we define a simple struct to store network information.

package main

...
import "net"

type NetworkInfo struct {
	HostName      string     `json:"host_name"`
	IPAddresses   []net.IP   `json:"ip_addresses"`
	MACAddresses  []net.HardwareAddr `json:"mac_addresses"`
	DefaultGateway net.IP    `json:"default_gateway"`
	DNSservers    []net.IP   `json:"dns_servers"`
}

This struct consists of five fields, each with a json tag to specify the JSON key's name.

Create an Instance of Your Struct

Once we have defined the struct, we can create an instance of the struct and assign some values to it:

package main

import (
	"fmt"
	"net"
)

type NetworkInfo struct {
	HostName      string           `json:"host_name"`
	IPAddresses   []net.IP         `json:"ip_addresses"`
	MACAddresses  []net.HardwareAddr `json:"mac_addresses"`
	DefaultGateway net.IP          `json:"default_gateway"`
	DNSservers    []net.IP         `json:"dns_servers"`
}

func main() {
    // Parse IP and HardwareAddr
	ip1 := net.ParseIP("192.168.1.1")
	ip2 := net.ParseIP("192.168.1.2")
	dns1 := net.ParseIP("8.8.8.8")
	dns2 := net.ParseIP("8.8.4.4")
	mac, _ := net.ParseMAC("00:00:5e:00:53:01")

	networkInfo := NetworkInfo{
		HostName: "my-computer",
		IPAddresses: []net.IP{
			ip1,
			ip2,
		},
		MACAddresses: []net.HardwareAddr{
			mac,
		},
		DefaultGateway: ip1,
		DNSservers: []net.IP{
			dns1,
			dns2,
		},
	}
    // json conversion code goes below here.
}

Marshal the Struct to JSON

Once we have the struct data, we can use the json.Marshal function to convert the struct to JSON:

jsonData, err := json.Marshal(networkInfo)

The json.Marshal function returns two values: a byte slice that represents the JSON data, and an error that will be nil if the process was successful.

Always remember to handle errors:

if err != nil {
	fmt.Println(err)
}

Lastly, convert the byte slice to a string and print it:

fmt.Println(string(jsonData))

Complete Code

Let's combine all the steps into a complete program:

package main

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

type NetworkInfo struct {
	HostName       string             `json:"host_name"`
	IPAddresses    []net.IP           `json:"ip_addresses"`
	MACAddresses   []net.HardwareAddr `json:"mac_addresses"`
	DefaultGateway net.IP             `json:"default_gateway"`
	DNSservers     []net.IP           `json:"dns_servers"`
}

func main() {
	// Parse IP and HardwareAddr
	ip1 := net.ParseIP("192.168.1.1")
	ip2 := net.ParseIP("192.168.1.2")
	dns1 := net.ParseIP("8.8.8.8")
	dns2 := net.ParseIP("8.8.4.4")
	mac, _ := net.ParseMAC("00:00:5e:00:53:01")

	networkInfo := NetworkInfo{
		HostName: "my-computer",
		IPAddresses: []net.IP{
			ip1,
			ip2,
		},
		MACAddresses: []net.HardwareAddr{
			mac,
		},
		DefaultGateway: ip1,
		DNSservers: []net.IP{
			dns1,
			dns2,
		},
	}
	// json conversion code goes below here.
	jsonData, err := json.Marshal(networkInfo)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(jsonData))
}

We can run the code above:

go run .

The program above should return an output as shown:

{"host_name":"my-computer","ip_addresses":["192.168.1.1","192.168.1.2"],"mac_addresses":["AABeAFMB"],"default_gateway":"192.168.1.1","dns_servers":["8.8.8.8","8.8.4.4"]}

We can pipe the output to JSON parsing tools such as jq to get a better output as shown:

go run . | jq

Output:

{
  "host_name": "my-computer",
  "ip_addresses": [
    "192.168.1.1",
    "192.168.1.2"
  ],
  "mac_addresses": [
    "AABeAFMB"
  ],
  "default_gateway": "192.168.1.1",
  "dns_servers": [
    "8.8.8.8",
    "8.8.4.4"
  ]
}

Conclusion

In this tutorial, we learned the basics of using the marshall function to convert a Go struct into a valid JSON object.

Share
Comments
More from GeekBits

Join us at GeekBits

Join our members and get a currated list of awesome articles each month.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to GeekBits.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.