JSON Encoding in Golang
To convert Go data structures to JSON (serialization), use json.Marshal. Here are examples with different data types:
//go:generate goversioninfo
package main
import (
"encoding/json"
"fmt"
)
func main() {
// Encode a map to JSON
mapData := map[string]int{"user_id": 9527, "role": 1}
encodedMap, _ := json.Marshal(mapData)
fmt.Println(string(encodedMap))
// Encode a slice to JSON
sliceData := []string{"foo", "bar", "baz"}
encodedSlice, _ := json.Marshal(sliceData)
fmt.Println(string(encodedSlice))
// Encode a struct to JSON
type Employee struct {
ID int `json:"employee_id"`
Name string `json:"employee_name"`
Dept string `json:"department"`
Years int `json:"years_of_service"`
}
emp := Employee{
ID: 101,
Name: "Bob",
Dept: "Engineering",
Years: 5,
}
encodedEmp, _ := json.Marshal(emp)
fmt.Println(string(encodedEmp))
}
JSON Decodnig in Golang
To convert JSON data to Go types, use json.Unmarshal. Here are examples with different targets:
//go:generate goversioninfo
package main
import (
"encoding/json"
"fmt"
)
func main() {
// Decode JSON to a map
jsonMapStr := `{"username":"john_doe","score":95,"country":"USA"}`
var mapResult map[string]interface{}
_ = json.Unmarshal([]byte(jsonMapStr), &mapResult)
fmt.Println(mapResult)
// Decode JSON to a slice
jsonSliceStr := `["apple", "banana", "cherry"]`
var sliceResult []string
_ = json.Unmarshal([]byte(jsonSliceStr), &sliceResult)
fmt.Println(sliceResult)
// Decode JSON to a struct
type User struct {
Username string `json:"username"`
Score int `json:"score"`
Country string `json:"country"`
}
var user User
_ = json.Unmarshal([]byte(jsonMapStr), &user)
fmt.Println(user.Username, user.Score, user.Country)
}
Empty Interface (interface{})
The empty interface interface{} can hold any value. Here's how to use it with type asertion and type switching:
package main
import "fmt"
func main() {
// Assign different types to an empty interface
var anyVal interface{}
anyVal = "sample text"
anyVal = 1999
anyVal = 2.718
// Type assertion
val, ok := anyVal.(float64)
fmt.Println(val, ok)
// Type switch
switch valType := anyVal.(type) {
case int:
fmt.Println("Type is integer")
case string:
fmt.Println("Type is string")
case float64:
fmt.Println("Type is float64")
default:
fmt.Println("Unknown type")
}
}
Decoding Arbitrary JSON
To decode JSON with unknown structure, use a map of interface{}:
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonData := `{"product":"Laptop", "price":999.99, "stock":50, "brand":"XYZ"}`
var arbitrary interface{}
_ = json.Unmarshal([]byte(jsonData), &arbitrary)
dataMap := arbitrary.(map[string]interface{})
for key, value := range dataMap {
fmt.Println(key, value)
}
}