how to convert struct to json in golang?
August 12, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To convert struct to json in golang, use the json.Marshal()
method it will convert your struct to JSON and return the converted JSON object.
Follow the below tutorial if you are struggling with installing GO in windows.
https://aguidehub.com/blog/how-to-install-golang-in-windows/
Today, I will show you how do i convert struct to JSON in golang, as above mentioned I’m going to use the json.Marshal()
method.
To use the json.Marshal()
method, we have first import "encoding/json"
package which is built in provided by golang, then we have to pass our struct with assignable variable in json.Marshal()
method.
Let’s start our Golang convert struct to JSON example
main.go
package main
import (
"encoding/json"
"fmt"
)
type Message struct {
Name string
Version int64
Code int64
}
func main() {
s := &Message{Name: "Android", Version: 13, Code: 1}
b, err := json.Marshal(s)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}
In the above example, we have converted a object to JSON and printed it in the console. let’s check the output.
Output
{"Name":"Android","Version":13,"Code":1}
I hope it helps you, All the best 👍.