In this source code example, we show how to convert Struct to JSON in Golang.
JSON (JavaScript Object Notation) is a lightweight data interchange format.
In Golang, the encoding/json package implements the encoding and decoding of JSON.
Go - Convert Struct to JSON
In the example, we transform a Go struct into JSON format:
package main
import (
"encoding/json"
"fmt"
"log"
)
type Employee struct {
Id int
FirstName string
LastName string
Email string
}
func main() {
e1 := Employee{1, "John", "Cena", "john@gmail.com"}
json_data, err := json.Marshal(e1)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(json_data))
}
Output:
{"Id":1,"FirstName":"John","LastName":"Cena","Email":"john@gmail.com"}
We declare the Employee struct:
type Employee struct {
Id int
FirstName string
LastName string
Email string
}
We create the struct instance:
e1 := Employee{1, "John", "Cena", "john@gmail.com"}
We encode the u1 struct into JSON with Marshal.
json_data, err := json.Marshal(e1)
Since json_data is a byte array, we convert it to a string with the string function:
fmt.Println(string(json_data))