JSON and Data Exchange
Encode Collections
Small slices and maps can be represented as JSON arrays and objects.
Encode Collections
encode_collections.go
package main
import (
"fmt"
)
func main() {
var apples =
counts := map[string]int{
"apples": apples,
"oranges": 2,
}
total := counts["apples"] + counts["oranges"]
text := fmt.Sprintf(`{"apples":%d,"oranges":%d}`, counts["apples"], counts["oranges"])
fmt.Println("apples=", counts["apples"])
fmt.Println("total=", total)
fmt.Println("json=", text)
}
package main
import (
"fmt"
)
func main() {
var apples =
counts := map[string]int{
"apples": apples,
"oranges": 2,
}
total := counts["apples"] + counts["oranges"]
text := fmt.Sprintf(`{"apples":%d,"oranges":%d}`, counts["apples"], counts["oranges"])
fmt.Println("apples=", counts["apples"])
fmt.Println("total=", total)
fmt.Println("json=", text)
}
package main
import (
"fmt"
)
func main() {
var apples =
counts := map[string]int{
"apples": apples,
"oranges": 2,
}
total := counts["apples"] + counts["oranges"]
text := fmt.Sprintf(`{"apples":%d,"oranges":%d}`, counts["apples"], counts["oranges"])
fmt.Println("apples=", counts["apples"])
fmt.Println("total=", total)
fmt.Println("json=", text)
}
collection encoding
JSON arrays and objects map naturally to Go slices and maps when the values are small and deterministic.