Compound Data
JSON and Go
maps
map[KeyType]ValueType
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
func main() {
m := make(map[string]Vertex)
m["Bell Labs"] = Vertex{40.68433, -74.39967}
fmt.Println(m)
m["Google"] = Vertex{37.42202, -122.08408}
fmt.Println(m)
val, ok := m["Bell Labs"]
fmt.Println("The value for Bell Labs:", val, "Present?", ok)
val1, ok1 := m["Microsoft"]
fmt.Println("The value for Microsoft:", val1, "Present?", ok1)
delete(m, "Google")
fmt.Println(m)
m["Bell Labs"] = Vertex{37.42202, -122.08408}
fmt.Println(m)
}
JSON to map
encoding/json
package main
import (
"encoding/json"
"fmt"
)
func main() {
var jsonBlob = []byte(`[
{"Name": "Platypus", "Order": "Monotremata"},
{"Name": "Quoll", "Order": "Dasyuromorphia"}
]`)
type Animal struct {
Name string
Order string
}
var animals []Animal
err := json.Unmarshal(jsonBlob, &animals)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v", animals)
}
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
type ColorGroup struct {
ID int
Name string
Colors []string
}
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
b, err := json.Marshal(group)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
}