業余時間玩 Golang。嘗試執行典型的 Web 任務:從 GET 請求中獲取 json 并打印其值。type Weather struct { name string}// some codedecoder := json.NewDecoder(res.Body)for { var weather Weather if err := decoder.Decode(&weather); err == io.EOF { break } else if err != nil { log.Fatal(err) } fmt.Println(weather.name) }JSON:{"coord":{"lon":145.77,"lat":-16.92},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"base":"stations","main":{"temp":300.15,"pressure":1007,"humidity":74,"temp_min":300.15,"temp_max":300.15},"visibility":10000,"wind":{"speed":2.6,"deg":260},"clouds":{"all":20},"dt":1455633000,"sys":{"type":1,"id":8166,"message":0.0314,"country":"AU","sunrise":1455567124,"sunset":1455612583},"id":2172797,"name":"Cairns","cod":200}據我了解,我需要聲明一個結構來獲取 json 值,但它不打印任何內容。我的錯誤是什么?如果我需要操作帶有未知字段的json怎么辦?有沒有辦法直接從json構造地圖?
1 回答

蝴蝶刀刀
TA貢獻1801條經驗 獲得超8個贊
您結構中的“名稱”字段Weather未導出。必須為其他包導出字段類型才能看到它們(因此,解組/解碼到它們中):https : //tour.golang.org/basics/3
您也可以使用結構標記將 Go 字段名稱映射到 JSON 鍵:
type Weather struct {
Name string `json:"name"`
}
...而在未來,您可以使用https://mholt.github.io/json-to-go/從 JSON 自動生成 Go 結構。
- 1 回答
- 0 關注
- 157 瀏覽
添加回答
舉報
0/150
提交
取消