Golang – Encode Json data

This recipe demonstrates how to use struct to encode to json data.

The struct type and its attributes have to be exportable in order for json encoding. The json data uses the attributes of struct type as keys if there is no customize key name defined.

package main

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

// Switch ...
type Switch struct {
	// `json:"hostname"` for example is to customize the name of the key in json data.
	Hostname string   `json:"hostname"`
	IPAddr   string   `json:"ip"`
	Vlan     []uint   `json:"vlans"`
	Intf     []string `json:"interfaces"`
}

func main() {
	sw1 := Switch{
		Hostname: "sw1",
		IPAddr:   "192.168.1.10",
		Vlan: []uint{
			10,  // frontend office
			20,  // backend office
			30,  // customer service office
			40,  // server
			999, // isolated vlan
		},
		Intf: []string{
			"Ethernet0/0",
			"Ethernet0/1",
			"Ethernet0/2",
			"Ethernet0/3",
			"Ethernet0/4",
			"Ethernet1/0",
			"Ethernet1/1",
			"Ethernet1/2",
			"Ethernet1/3",
			"Ethernet1/4",
		},
	}

	// jsonData, err := json.Marshal(sw1)
	// Encode to json, json.MarshalIndent() is to make printing pretty.
	jsonData, err := json.MarshalIndent(sw1, "", " ")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(jsonData))
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s