JSON Handling in Go
# CHAPTER 22
JSON Handling in Go
1. Introduction
Modern applications do not exist in isolation. If your Go backend needs to talk to a React frontend, a mobile app, or a Stripe payment gateway, it must speak the universal language of the web: JSON (JavaScript Object Notation). In this chapter, we will learn how to use Go's standardencoding/json package to convert Go Structs into JSON (Marshaling), and convert incoming JSON back into Go Structs (Unmarshaling).
2. Learning Objectives
By the end of this chapter, you will be able to:-
Convert a Go Struct into a JSON string (
Marshal).
-
Convert a JSON string into a Go Struct (
Unmarshal).
- Understand and apply Struct Tags.
- Handle unknown JSON structures.
3. Struct Tags (The Secret Ingredient)
In Go, exported struct fields MUST be capitalized (e.g.,FirstName). However, standard JSON uses lowercase or snakecase (e.g., "firstname").
To bridge this gap, Go uses Struct Tags. These are backtick-quoted strings placed after the struct field. They tell the JSON encoder exactly how to format the keys.
4. Encoding (Marshaling) to JSON
To convert a Struct into a slice of JSON bytes, we usejson.Marshal().
Output:
{"id":1,"first_name":"Alice"}
*(Notice how the Email was omitted, the Password was hidden, and the keys are lowercase!)*
5. Decoding (Unmarshaling) from JSON
When a frontend sends JSON data to your server, you need to parse it back into a Go Struct. We usejson.Unmarshal().
Critical Memory Rule: You must pass a Pointer (&) of your struct to Unmarshal, so it can write the parsed data directly into your variable's memory address!
6. Dealing with Unknown JSON (Unstructured Data)
What if an external API sends you JSON, but you don't know the structure in advance, so you can't build a Struct for it? You can unmarshal the JSON into a flexiblemap[string]interface{} (A map where the keys are strings, and the values can be literally anything).
*(Note: While this works, using strongly-typed Structs is always preferred in Go for performance and safety).*
7. Common Mistakes
-
Unexported Struct Fields: If your struct field is lowercase (
name stringinstead ofName string), thejsonpackage (which is an external package) cannot see it. It will silently ignore the field, and your generated JSON will be mysteriously empty. Always capitalize struct fields used for JSON!
-
Forgetting the Pointer in Unmarshal: Calling
json.Unmarshal(data, newUser)instead of&newUser. Go will return an error because it cannot modify a copy of the struct.
8. Best Practices
-
Pretty Print: If you are debugging and want human-readable JSON with indents and newlines, use
json.MarshalIndent(u, "", " ")instead of standard Marshal.
9. Exercises
-
1.
Create a
Productstruct withName,Price, andInStockfields. Use struct tags to make them lowercase in JSON.
-
2.
Instantiate a
Product, Marshal it to JSON, and print the resulting string.
10. MCQs with Answers & Explanations
Which standard library package is used to handle JSON in Go?
What is the process of converting a Go Struct into a JSON string called?
What is the process of converting a JSON string into a Go Struct called?
What is the primary purpose of Struct Tags (e.g., ` json:"id" )?
What does the struct tag json:"-" do?
What happens if a struct field is named password (lowercase 'p') when Marshaling?
What data type does json.Marshal() output?
, why MUST you use an ampersand (&)?
a) Because Unmarshal requires a pointer to write the parsed data directly into the struct's memory b) It looks cool
Answer: a) Because Unmarshal requires a pointer.
If you receive totally random, unknown JSON, what data type can you unmarshal it into?
What function produces human-readable, formatted JSON with indents?
11. Interview Preparation
Interview Questions:-
1.
Why must struct fields be capitalized to be converted to JSON? (Answer: Because the encoding/json
package is an external package, and Go's visibility rules state that only capitalized fields are exported/visible outside the package).
-
2.
How do you exclude a field from being marshaled into JSON? (Answer: Using the json:"-"
struct tag).
12. Summary
JSON handling in Go relies on Structs and Struct Tags. By defining rigid data models, Go ensures that APIs are type-safe and predictable. Marshal encodes our data for the web, and Unmarshal decodes incoming web data into memory.
13. Next Chapter Recommendation
Now that we can speak the language of the web (JSON), it is time to build a web server! In Chapter 23: Building REST APIs in Go, we will use the net/http` package to open a network port, listen for requests, and return real JSON responses to a browser.