forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example2.go
64 lines (54 loc) · 1.53 KB
/
example2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// Sample program to show how to unmarshal a JSON document into
// a user defined struct type from a file.
package main
import (
"encoding/json"
"fmt"
"os"
)
type (
// buoyCondition contains information for an individual station.
buoyCondition struct {
WindSpeed float64 `json:"wind_speed_milehour"`
WindDirection int `json:"wind_direction_degnorth"`
WindGust float64 `json:"gust_wind_speed_milehour"`
}
// buoyLocation contains the buoys location.
buoyLocation struct {
Type string `json:"type"`
Coordinates []float64 `json:"coordinates"`
}
// BuoyStation contains information for an individual station.
buoyStation struct {
StationID string `json:"station_id"`
Name string `json:"name"`
LocDesc string `json:"location_desc"`
Condition buoyCondition `json:"condition"`
Location buoyLocation `json:"location"`
}
)
func main() {
// Open the file.
file, err := os.Open("data.json")
if err != nil {
fmt.Println("Open File", err)
return
}
// Schedule the file to be closed once
// the function returns.
defer file.Close()
// Decode the file into a slice of buoy stations.
var stations []buoyStation
err = json.NewDecoder(file).Decode(&stations)
if err != nil {
fmt.Println("Decode File", err)
return
}
// Iterate over the slice and display
// each station.
for _, station := range stations {
fmt.Printf("%+v\n\n", station)
}
}