How to Convert Struct to JSON in Golang

To convert a Struct to JSON in Golang, you can use the “json.Marshal()” function. The json.Marshal() function encodes a struct into a JSON-formatted byte slice.

Example

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}

In this example, we defined a Student struct with two fields: Name and Age. The json struct tags specify the JSON field names that should be mapped to the corresponding struct fields.

In the next step, we created a Student variable and populated it with data.

Next, we used the json.Marshal() function to encode the person struct into a JSON-formatted byte slice.

If there is an error during the encoding process, the program will log the error and exit.

Finally, we converted the byte slice to a string and printed the resulting JSON string to the console.

Leave a Comment