Json
sample.json
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"pref": "富山県",
"city1": "下新川郡",
"city2": "朝日町"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
136.111111,
36.111111
],
[
136.222222,
36.222222
]
]
]
}
},
{
"type": "Feature",
"properties": {
"pref": "富山県",
"city1": "氷見市",
"city2": ""
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
136.333333,
36.333333
],
[
136.444444,
36.444444
]
]
]
}
},
{
"type": "Feature",
"properties": {
"pref": "富山県",
"city1": "高岡市",
"city2": ""
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
136.555555,
36.555555
],
[
138.666666,
36.666666
]
]
]
}
}
]
}
Jsonと対になる構造体を用意したGo
main.go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
type FeatureCollection struct {
Type string `json:"type"`
Features []Feature `json:"features"`
}
type Feature struct {
Type string `json:"type"`
Properties Properties `json:"properties"`
Geometory Geometry `json:"geometry"`
}
type Properties struct {
Pref string `json:"pref"`
City1 string `json:"city1"`
City2 string `json:"city2"`
}
type Geometry struct {
Type string `json:"type"`
Coordinates [][]LatLng `json:"coordinates"`
}
type LatLng [2]float64
func main() {
raw, err := ioutil.ReadFile("./sample.json")
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
var fc FeatureCollection
json.Unmarshal(raw, &fc)
for _, ft := range fc.Features {
fmt.Println(ft.Type)
fmt.Println(ft.Properties.Pref, ft.Properties.City1, ft.Properties.City2)
fmt.Println(ft.Geometory.Type)
fmt.Println(ft.Geometory.Coordinates[0][0][0], ft.Geometory.Coordinates[0][0][1])
}
}
実行結果
go run main.go
Feature
富山県 下新川郡 朝日町
Polygon
136.111111 36.111111
Feature
富山県 氷見市
Polygon
136.333333 36.333333
Feature
富山県 高岡市
Polygon
136.555555 36.555555