Skip to content

Golang: Simple Marshal Struct to JSON

In Golang convert an object to JSON string (or a slice of bytes) is so simple by using the json package:

func json.Marshal(v interface{}) ([]byte, error)

In this example you can see how to marshal in golang:

package main

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

func main() {

	type User struct {
		Name string
		Age  int
		Tags []string
	}

	userData := User{
		Name: "Morteza",
		Age:  23,
		Tags: []string{"Active", "Pro"},
	}

	// jsonBytes is a slice of bytes
	jsonBytes, err := json.Marshal(userData)
	if err != nil {
		log.Fatalf("failed to marshal: %s", err)
	}

	// Simply convert it to string 
	fmt.Println("json:", string(jsonBytes))
}

Leave a Reply

Your email address will not be published. Required fields are marked *