亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 json.Decoder 獲取鍵和值

從 json.Decoder 獲取鍵和值

Go
飲歌長嘯 2021-12-13 18:41:48
業余時間玩 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 結構。


查看完整回答
反對 回復 2021-12-13
  • 1 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號