Encoding Structs into JSON in Go

Introduction to JSON Encoding in Go

Welcome back! In the previous lesson, we explored the basics of JSON and how Go uses structs to manage and organize JSON data. You learned how to define a struct in Go and use struct tags for JSON serialization. This foundational knowledge is crucial as we move forward to more advanced topics. In this lesson, we will focus on encoding Go structs into JSON format, a process known as marshaling. This is an essential skill for interacting with APIs, as JSON is the primary data format for most web services. By the end of this lesson, you will be able to seamlessly convert Go structs into JSON, preparing you for effective API communication.

Encoding Go Structs into JSON

To encode a Go struct into JSON, we use the encoding/json package, which provides the json.Marshal function. This function takes a Go struct and converts it into a JSON-encoded byte slice. Let's revisit the Todo struct from the previous lesson and see how we can marshal it into JSON.

package main

import (
    "encoding/json"
    "log"
)

// Todo structure represents a task with 'title' and 'done' status
type Todo struct {
    Title       string `json:"title"`
    Done        bool   `json:"done"`
    Description string `json:"description"`
}

func main() {
    // Create a new instance of Todo
    todo := Todo{
        Title:       "Walking the dog",
        Done:        false,
        Description: "Walking the dog in the park",
    }

    // Convert Todo instance to JSON format
    jsonTodo, err := json.Marshal(todo)
    if err != nil {
        log.Fatalf("Error occurred during marshalling: %s", err.Error())
    }

    // Print the JSON object
    log.Printf("JSON object: %s", jsonTodo)
}

In this example, we define a Todo struct with fields Title, Done, and Description. Each field has a JSON tag that specifies the key name in the resulting JSON object. We create an instance of Todo and use json.Marshal to convert it into JSON. If successful, the JSON object is printed. The output will be a JSON string representing the Todo object, such as:

JSON object: {"title":"Walking the dog","done":false,"description":"Walking the dog in the park"}

Practical Example: Sending JSON Data via HTTP

Step 1: Convert Struct to JSON

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal