How to Convert Struct to JSON in Golang

1. Introduction

JSON (JavaScript Object Notation) is widely used in web and database programming as a way to structure data. In Go, encoding a struct to JSON is a common task that can be easily accomplished using the standard encoding/json package. This post will explain how to convert a Go struct to a JSON string.

Definition

A struct in Go is a composite data type that groups together variables under a single name for easy data manipulation. Converting a struct to JSON involves translating this structured data into a JSON string representation.

2. Program Steps

1. Define a struct with exported fields.

2. Use the json.Marshal function to convert the struct to JSON.

3. Handle any errors that may occur during the conversion.

4. Print the JSON string.

3. Code Program

package main

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

// User defines a user with a name, age, and a list of social followers.
type User struct {
	Name       string   `json:"name"`
	Age        int      `json:"age"`
	Followers  []string `json:"followers,omitempty"`
	Occupation string   `json:"occupation,omitempty"`
}

func main() {
	// Step 1: Define a struct with exported fields
	user := User{
		Name:      "Alice",
		Age:       25,
		Followers: []string{"Bob", "Charlie"},
		// Occupation field is intentionally left zero-value to demonstrate "omitempty"
	}

	// Step 2: Convert the struct to JSON
	userJSON, err := json.Marshal(user)
	if err != nil {
		// Step 3: Handle errors
		log.Fatalf("Error converting struct to JSON: %s", err)
	}

	// Step 4: Print the JSON string
	fmt.Printf("%s\n", userJSON)
}

Output:

{"name":"Alice","age":25,"followers":["Bob","Charlie"]}

Explanation:

1. package main - The package declaration for the Go program.

2. import statements - Bringing in the fmt package for formatted I/O, the encoding/json package for JSON encoding, and the log package for logging errors.

3. User struct - This struct is defined with tags specifying JSON field names and includes the omitempty option to omit the field if it has a zero value.

4. user variable - An instance of User is created with values set to the fields Name, Age, and Followers.

5. json.Marshal - Used to convert user into a JSON byte slice. This function will only include exported fields (those starting with a capital letter) in the JSON output.

6. log.Fatalf - If marshaling encounters an error, this function logs the error message and exits the program.

7. fmt.Printf - Prints the JSON byte slice as a string to the console.

8. The output shows the struct user encoded as a JSON string. Notice the Occupation field is not included in the output because it was left as the zero value and omitempty is specified in the struct tag.


Comments