Introduction
JSON is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. In Go, working with JSON is made simple with the encoding/json package.
This blog will explore the fundamentals of JSON marshal/unmarshal and encode/decode in Go, when to use them, a comparison of their memory efficiency, and real-world examples.
What is JSON Marshal/Unmarshal and Encode/Decode?
JSON Marshal and Unmarshal
json.Marshal: Converts a Go data structure into a JSON encoded byte slice. It’s like converting a map, struct, or slice into a JSON string.

json.Unmarshal: Converts a JSON encoded byte slice into a Go data structure. This is useful for parsing JSON data received from an API or read from a file.

JSON Encode and Decode
json.NewEncoder: Writes JSON encoded data directly to anio.Writer. This method is efficient for streaming JSON data.

json.NewDecoder: Reads JSON encoded data directly from an io.Reader. It’s ideal for processing JSON data incrementally.

When Do We Use It?
Marshal/Unmarshal:
- Use when you need to work with JSON data in memory.
- Ideal for small to moderate-sized datasets.
- Suitable for situations where you need to manipulate the entire JSON data.
Encoder/Decoder:
- Use when dealing with large datasets or streaming data.
- More efficient for real-time data processing.
- They are preferred when working with files, network connections, or other I/O operations where data can be processed incrementally.
Memory Efficiency
Marshal/Unmarshal: These functions create intermediate byte slices that hold the entire JSON data in memory. This can be inefficient for large datasets as it requires significant memory allocation.Encoder/Decoder: These functions handle data incrementally, streaming the data through anio.Writerorio.Reader. This reduces memory usage and is more efficient for large datasets or real-time data processing.
Real-World Examples
Marshal Go Struct to JSON

Unmarshal JSON to a Go Struct (Reading configuration Files)

Encode (Return response to API)

Decode (Decode API response)

Closing Thoughts
Working with JSON in Go is straightforward with the right tools and knowledge. By understanding the differences and use cases for marshal/unmarshal and encode/decode, you can write more efficient and scalable Go applications. Happy coding 🙂
