To convert a Struct to JSON in Golang, you can “use the json.Marshal() function.”
Here is the step-by-step guide:
- Define a struct.
- Create an instance of the struct.
- Convert the struct to JSON using json.Marshal.
- Print the JSON string.
Let’s implement these steps in the program.
package main
import (
"encoding/json"
"fmt"
"log"
)
type Student struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
student := Student{Name: "Krunal Lathiya", Age: 30}
// Convert struct to JSON
jsonData, err := json.Marshal(student)
if err != nil {
log.Fatal(err)
}
fmt.Println("Struct as JSON:", string(jsonData))
}
Output
Struct as JSON: {"name":"Krunal Lathiya","age":30}
That’s it!
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.