How to Serialize JSON String in Go

To serialize json string in Golang, you can use the “json.Marshal()” function. The “json.Marshal()” function returns the JSON encoding of the interface.

Example

package main

import (
  "encoding/json"
  "fmt"
  "log"
)

 // Define a struct to represent a person
type Student struct {
  Name string `json:"name"`
  Age int `json:"age"`
}

func main() {
  // Create an instance of the Student struct
  student := Student{Name: "Krunal", Age: 30}

  // Serialize the student struct to JSON
  jsonBytes, err := json.Marshal(student)
  if err != nil {
    log.Fatalf("Error marshaling JSON: %v", err)
  }

  // Convert the JSON bytes to a string and print it
  jsonString := string(jsonBytes)
  fmt.Println("JSON string:", jsonString)
}

Output

JSON string: {"name":"Krunal","age":30}

In this code, we defined a Student struct with Name and Age fields.

In the next step, we created an instance of the Student struct and use the json.Marshal() function to serialize it into a JSON-formatted byte slice (jsonBytes). We then convert jsonBytes to a string (jsonString) and print it.

Note the struct field tags like json:”name” and json:”age”.

These tags specify the JSON key names when marshaling and unmarshaling the struct.

If you don’t provide these tags, the field names in the struct will be used as JSON key names, with the first letter capitalized by default.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.