Last updated on Jun 19, 2021 by Suraj Sharma
In this tutorial, you will learn to convert a Golang struct data type to a JSON string using package json
by importing encoding/json
import "encoding/json"
To convert a struct data type to a JSON string we use the Marshal
function
package main
import (
"encoding/json"
"fmt"
)
type Post struct {
ID uint `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
Content string `json:"content"`
}
func main () {
// create an instance of Post struct
post := Post{
ID: 1,
Title: "Golang Tutorial",
Content: "Learn Golang by examples",
Author: "Suraj Sharma",
}
// use json.Marshal to convert the post to a []byte of JSON data
b, err := json.Marshal(post)
if err != nil {
fmt.Println("Unable to convert the struct to a JSON string")
} else {
// convert []byte to a string type and then print
fmt.Println(string(b))
}
}
// output
// {"id":1,"title":"Golang Tutorial","author":"Suraj Sharma","content":"Learn Golang by examples"}
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.