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 (

// 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:   "",
		Vlan: []uint{
			10,  // frontend office
			20,  // backend office
			30,  // customer service office
			40,  // server
			999, // isolated vlan
		Intf: []string{

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


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 )

Facebook photo

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

Connecting to %s