How to Convert Struct to JSON in Golang

To convert a Struct to JSON in Golang, you can “use the json.Marshal() function.” 

Here is the step-by-step guide:

  1. Define a struct.
  2. Create an instance of the struct.
  3. Convert the struct to JSON using json.Marshal.
  4. 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

Go json to struct

Go map to struct

Go struct to string

Go interface to struct