Introduction to Working with JSON in Go
JSON (JavaScript Object Notation) is a lightweight data interchange format widely used in web development, APIs, and configuration files. The Go language (Golang) provides a built-in package encoding/json that allows you to easily parse (decode) and serialize (encode) data. In this article, we will cover the basics of working with JSON in Go using practical examples that are understandable even for beginner developers.
Basics of the encoding/json Package
The encoding/json package is a standard Go library that requires no additional installation. The two main tools in this package are the json.Marshal (serialization) and json.Unmarshal (deserialization) functions.
Structures and JSON Tags
In Go, data is typically represented as structures (struct). Tags are used to control the names of fields in JSON. Let's look at a simple example:
package main
import ( "encoding/json" "fmt")
// Define a structure with JSON tagstype Person struct { Name string `json:"name"` Age int `json:"age"` Email string `json:"email,omitempty"` IsAdmin bool `json:"is_admin"`}
func main() { // Create an instance of the structure person := Person{ Name: "Ivan Petrov", Age: 30, Email: "ivan@example.com", IsAdmin: true, } // Serialize to JSON jsonData, _ := json.Marshal(person) fmt.Println(string(jsonData))}Execution result:
{"name":"Ivan Petrov","age":30,"email":"ivan@example.com","is_admin":true}Important points:
- The tag
json:"name"specifies how the field will be named in JSON - The
omitemptyoption skips empty fields (zero values) - Structure fields must be exported (start with a capital letter)
Serialization (Marshal) of Data to JSON
Serialization is the process of converting a Go structure or other data type into a JSON string. The json.Marshal function returns a byte slice ([]byte) and an error.
Examples of Serializing Different Types
package main
import ( "encoding/json" "fmt")
type Product struct { ID int `json:"id"` Name string `json:"name"` Price float64 `json:"price"` Tags []string `json:"tags,omitempty"` InStock bool `json:"in_stock"`}
func main() { // Serialize a structure product := Product{ ID: 101, Name: "Laptop", Price: 79999.99, Tags: []string{"electronics", "laptops"}, InStock: true, } // Pretty print with indentation jsonData, _ := json.MarshalIndent(product, "", " ") fmt.Println(string(jsonData)) // Serialize a slice of structures products := []Product{ {ID: 1, Name: "Mouse", Price: 1500.00, InStock: true}, {ID: 2, Name: "Keyboard", Price: 3500.00, InStock: false}, } jsonArray, _ := json.Marshal(products) fmt.Println(string(jsonArray))}Result:
{ "id": 101, "name": "Laptop", "price": 79999.99, "tags": [ "electronics", "laptops" ], "in_stock": true}[{"id":1,"name":"Mouse","price":1500,"in_stock":true},{"id":2,"name":"Keyboard","price":3500,"in_stock":false}]Parsing (Unmarshal) JSON in Go
Parsing is the reverse process: converting a JSON string into a Go structure. The json.Unmarshal function is used for this.
Basic Parsing Example
package main
import ( "encoding/json" "fmt" "log")
type User struct { Username string `json:"username"` Age