The Most Crucial Data Interchange Format In Programming


๐ Understanding JSON in Go: A Complete Guide
JSON (JavaScript Object Notation) is one of the most common data formats used in web development, APIs, and modern applications. If you're interchanging data between a server to client, you have to understand JSON. As a Developer, understanding how your language handles JSON is essential for building real-world applications.
๐งฉ What is JSON?
JSON is a lightweight, text-based format for structuring data. It's language-independent, but it originated from JavaScript. It's widely used for data exchange between a client and a server in web applications.
Example JSON:
{
"name": "Hasib",
"age": 25,
"skills": ["Go", "JavaScript"]
}
๐ JSON Use Cases:
JSON is commonly used for:
RESTful API request/response bodies
Config files
Data serialization/deserialization
Inter-service communication, etc
As a Go Developer, let's explore JSON in Go:
๐ ๏ธ JSON Implementation in Go
Go uses the encoding/json
standard package to handle JSON. You can use two main approaches. First approach Marshal
and Unmarshal
They are used when you already have the full JSON data in memory. And the second approach Encoder
and Decoder
are used when you're working with streams (e.g, reading JSON from a file or HTTP body):
1. Marshal
and Unmarshal
Go is a static type language, so you can't write JSON directly. First, you need to create a struct. These functions Marshal
and Unmarshal
are used to convert the structs to JSON (Marshal) and JSON to structs (Unmarshal).
๐ Let's see an example:(Struct โ JSON)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Skills []string `json:"skills"`
}
๐นStruct to JSON
// Struct to JSON
user := User{"Hasib", 25, []string{"Go", "JavaScript"}}
jsonData, _ := json.Marshal(user)
fmt.Println(string(jsonData))
//output: {"name":"Hasib","age":25,"skills":["Go","JavaScript"]}
๐นJSON to Struct
// JSON to Struct
jsonString := `{
"name":"Hasib",
"age":25,
"skills":["Go","JavaScript"]
}`
var parsedUser User
json.Unmarshal([]byte(jsonString), &parsedUser)
fmt.Println(parsedUser.Name)
//output: Hasib
2. Encoder
and Decoder
These are used for streaming JSON to and from I/O sources (e.g., HTTP requests/responses).
// Reading JSON from HTTP request
json.NewDecoder(r.Body).Decode(&user)
// Writing JSON to HTTP response
json.NewEncoder(w).Encode(user)
These are especially useful in building web servers.
๐ Note: I'm from a JavaScript background. JavaScript is my first language. So I had a little trouble understanding it at first. If you are already familiar with it, you can skip this section.
๐ Comparison: JSON in Go vs JavaScript
Feature | JavaScript | Go |
Data Structure | Dynamic object {} | Typed struct |
Serialize Object | JSON.stringify(obj) | json.Marshal(struct) |
Deserialize JSON | JSON.parse(jsonString) | json.Unmarshal([]byte, &struct) |
JSON Tags | Not needed | Required: json:"fieldName" |
Optional Fields | Can be missing | Use omitempty , pointer types, or default |
Field Visibility | All fields visible | Must be exported (Capitalized fields) |
Streaming (I/O) Support | Implicit in fetch/AJAX | Use json.Encoder / json.Decoder |
๐ธ JS Object
const user = { name: "Hasib", age: 25 };
๐น Go Struct
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
๐ Real-world REST API Example (in Go)
func userHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
var user User
json.NewDecoder(r.Body).Decode(&user)
json.NewEncoder(w).Encode(map[string]string{"message": "User created"})
}
}
๐ Key Takeaways of Go JSON:
Use
structs
withjson
tags for mapping JSON data.Use
Marshal
/Unmarshal
for in-memory data.Use
Encoder
/Decoder
for reading/writing to streams (like HTTP).Struct field names must be exported (start with uppercase) to be serialized.
public/privet
concept from OOP.
Mastering JSON handling is your gateway to writing web servers, clients, and APIs in Go โ and it's easier when you think of it like a type-safe version of JavaScript's object manipulation.
โ Conclusion
Working with JSON in Go is simple and robust once you understand the basics of structs, field tags, and the encoding/json
package. While Go is more strict and typed compared to JavaScript, this makes your data structures more predictable and secure.
Subscribe to my newsletter
Read articles from AL Hasib directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
