douben6670 2016-02-16 15:25
浏览 56
已采纳

从json.Decoder获取键和值

Playing with Golang in my spare time. Trying to perform typical web task: get json from GET request and print its values.

type Weather struct {
    name string
}
// some code
decoder := 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}

As I understand, I need to declare a struct to get json values, but it prints nothing. What is my mistake?

And what if I need to operate json with unknown fields? Is there a way to construct map directly from json?

  • 写回答

1条回答 默认 最新

  • douhui9631 2016-02-16 15:31
    关注

    Your 'name' field within your Weather struct is unexported. Field types must be exported for other packages to see them (and therefore, unmarshal/decode into them): https://tour.golang.org/basics/3

    You can use struct tags to map Go field names to JSON keys as well:

    type Weather struct {
        Name string `json:"name"`
    }
    

    ... and for the future, you can use https://mholt.github.io/json-to-go/ to auto-generate Go structs from JSON.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法