Go语言处理JSON数据,本文使用CitiBike数据为例。
package main
// 解析JSON数据
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
// citiBikeURL 提供了CitiBike共享单车的站点信息
const citiBikeURL = "https://gbfs.citibikenyc.com/gbfs/en/station_status.json"
// 定义station结构体接受数据
type station struct{
ID string `json:"station_id"`
NumBikesAvailable int `json:"num_bikes_available"`
NumBikesDIsabled int `json:"num_bikes_disabled"`
NumsDocksAvaliable int `json:"num_docks_available"`
NumsDocksDisabled int `json:"num_docks_disabled"`
IsInstalled int `json:"is_installed"`
IsRending int `json:"is_renting"`
IsReturning int `json:"is_returning"`
LastReported int `json:"last_reported"`
HasAvailableKeys bool `json:"eightd_has_available_keys"`
}
// 定义stationData结构体
type stationData struct{
LastUpdated int `json:"last_updated"`
TTL int `json:"ttl"`
Data struct{
Stations []station `json:"stations"`
} `json:"data"`
}
func main(){
// 建立Http连接,获取JSON respose
resp, err:= http.Get(citiBikeURL)
if err!= nil{
log.Fatal(err)
}
defer resp.Body.Close()
// 读取response中的数据
body, err:= ioutil.ReadAll(resp.Body)
if err!= nil{
log.Fatal(err)
}
var sd stationData
// Unmarshal json数据
if err:= json.Unmarshal(body, &sd); err!= nil{
log.Fatal(err)
}
// 打印数据
fmt.Printf("%+v\n",sd.Data.Stations[0])
}