12/04/2026 18:19pm

EP.13 Go and JSON - Making Data Conversion Easy!
#programming
#data handling
#Unmarshal
#Marshal
#JSON
#Go
Go and JSON - Making Data Conversion Easy!
Do you want your program's data to be easy to read and compatible with other applications? JSON is the answer! Today, we will teach you how to convert data to JSON and back to use in Go easily.
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read and write. It is commonly used for communicating and exchanging data between different programs, especially in applications that connect to APIs or servers.
Structure of JSON
JSON stores data in the form of "name": value pairs, for example:
In this example:
"name": "Alice" is a string.
"age": 25 is a number.
"isStudent": true is a boolean value.
{
"name": "Alice",
"age": 25,
"isStudent": true
}
Converting Data to JSON in Go (Encoding)
Converting data in Go to JSON is straightforward using the json.Marshal function with a struct to hold the data we want to convert.
Example:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
p := Person{Name: "Alice", Age: 25}
jsonData, err := json.Marshal(p)
if err != nil {
fmt.Println("Error encoding JSON:", err)
return
}
fmt.Println(string(jsonData)) // แสดงผล JSON เป็น string
}
In this example:
We create a struct called Person with fields Name and Age.
We use json.Marshal(p) to convert Person to JSON.
The result will be:
{"name":"Alice","age":25}
Converting JSON Back to Data in Go (Decoding)
When we have JSON and want to convert it back to a struct, we use json.Unmarshal.
In this example: We convert JSON (jsonData) back to a struct named Person using json.Unmarshal.
The result will display the name and age of the Person.
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
jsonData := []byte(`{"name":"Alice","age":25}`)
var p Person
err := json.Unmarshal(jsonData, &p)
if err != nil {
fmt.Println("Error decoding JSON:", err)
return
}
fmt.Println(p.Name, "is", p.Age, "years old.")
}
Summary
Use json.Marshal to convert data to JSON (Encoding).
Use json.Unmarshal to convert JSON back to data (Decoding).
JSON makes data easy to read and convenient for use with other applications.
You can try creating a struct with various fields such as name, age, and student status, then convert it to JSON and back to a struct to see if the data remains the same!