The Most Crucial Data Interchange Format In Programming

AL HasibAL Hasib
4 min read

๐Ÿ“˜ 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 Marshaland 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

FeatureJavaScriptGo
Data StructureDynamic object {}Typed struct
Serialize ObjectJSON.stringify(obj)json.Marshal(struct)
Deserialize JSONJSON.parse(jsonString)json.Unmarshal([]byte, &struct)
JSON TagsNot neededRequired: json:"fieldName"
Optional FieldsCan be missingUse omitempty, pointer types, or default
Field VisibilityAll fields visibleMust be exported (Capitalized fields)
Streaming (I/O) SupportImplicit in fetch/AJAXUse 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 with json 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.

0
Subscribe to my newsletter

Read articles from AL Hasib directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

AL Hasib
AL Hasib