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.
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:
Practical Example: Sending JSON Data via HTTP
Step 1: Convert Struct to JSON
