How to Use Map for JSON in Go: Simple Guide
In Go, you can use
map[string]interface{} to represent JSON objects dynamically. Use json.Unmarshal to decode JSON into this map and json.Marshal to encode it back to JSON.Syntax
Use map[string]interface{} to hold JSON objects where keys are strings and values can be any type. Use json.Unmarshal to convert JSON bytes into this map, and json.Marshal to convert the map back to JSON bytes.
map[string]interface{}: dynamic JSON objectjson.Unmarshal([]byte, &map): decode JSONjson.Marshal(map): encode JSON
go
var data map[string]interface{} err := json.Unmarshal(jsonBytes, &data) if err != nil { // handle error } jsonBytes, err = json.Marshal(data) if err != nil { // handle error }
Example
This example shows how to decode a JSON string into a map, access its values, modify them, and encode the map back to JSON.
go
package main import ( "encoding/json" "fmt" "log" ) func main() { jsonStr := `{"name":"Alice","age":30,"skills":["Go","Python"]}` var data map[string]interface{} err := json.Unmarshal([]byte(jsonStr), &data) if err != nil { log.Fatal(err) } fmt.Println("Original map:", data) // Access values name := data["name"].(string) age := data["age"].(float64) // JSON numbers decode as float64 fmt.Printf("Name: %s, Age: %.0f\n", name, age) // Modify map data["age"] = age + 1 data["city"] = "New York" // Encode back to JSON updatedJSON, err := json.Marshal(data) if err != nil { log.Fatal(err) } fmt.Println("Updated JSON:", string(updatedJSON)) }
Output
Original map: map[age:30 name:Alice skills:[Go Python]]
Name: Alice, Age: 30
Updated JSON: {"age":31,"city":"New York","name":"Alice","skills":["Go","Python"]}
Common Pitfalls
Common mistakes when using maps for JSON in Go include:
- Not using
interface{}as the map value type, which limits flexibility. - Forgetting that JSON numbers decode as
float64, so type assertions must match. - Not checking errors from
json.Unmarshalorjson.Marshal. - Incorrect type assertions causing panics.
Always check types carefully and handle errors.
go
var data map[string]string err := json.Unmarshal([]byte(`{"age":30}`), &data) // Wrong: map value type is string, but JSON has number // This will cause an error // Correct way: var correctData map[string]interface{} err = json.Unmarshal([]byte(`{"age":30}`), &correctData) if err != nil { // handle error }
Quick Reference
Summary tips for using map with JSON in Go:
- Use
map[string]interface{}for flexible JSON objects. - JSON numbers become
float64in Go. - Always check errors from JSON functions.
- Use type assertions carefully to avoid panics.
- Use
json.Marshalandjson.Unmarshalfor encoding and decoding.
Key Takeaways
Use map[string]interface{} to represent JSON objects dynamically in Go.
Decode JSON with json.Unmarshal and encode with json.Marshal.
JSON numbers decode as float64, so assert types carefully.
Always check errors when working with JSON functions.
Avoid panics by verifying types before using type assertions.