How To Convert A Struct to JSON in Go
Go has built-in packages that make it easy to encode and decode JSON data. In this tutorial we will guide you on how to convert a Struct to JSON in Go with easy-to-understand examples.
Prerequisites:
- The Go Compiler installed on your machine.
- A basic understanding of Go syntax and structures.
You can learn how to install Go on your system using the tutorials:
https://www.geekbits.io/how-to-install-golang-on-macos/
https://www.geekbits.io/how-to-install-golang-on-linux/
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)
}
Print the JSON Data
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.