dpdbu24262 2014-08-03 22:54
浏览 95
已采纳

Golang-无法解析JSON

I've started learning GO, and i have encountered this issue. I have this code

package main

import (
  "fmt"
  "encoding/json"
//  "net/html"
)


func main(){
  type Weather struct {
    name string
    cod float64
    dt float64
    id float64
  }

  var rawWeather = []byte(`{"name":"London","cod":200,"dt":1407100800,"id":2643743}`)
  var w Weather
  err := json.Unmarshal(rawWeather, &w)
  if err != nil {
    fmt.Println("Some error", err)
  }
  fmt.Printf("%+v
",w)
}

when i run it, it shows this

[nap@rhel projects]$ go run euler.go 
{name: cod:0 dt:0 id:0}

So, the JSON is not parsed into the weather struct.

Any ideas, why do this happens like this?

  • 写回答

3条回答 默认 最新

  • douwenan9849 2014-08-03 23:03
    关注

    By quessing, i found, that this code works:

    package main
    
    import (
      "fmt"
      "encoding/json"
    //  "net/html"
    )
    
    
    func main(){
      type Weather struct {
        Name string
        Cod float64
        Dt float64
        Id float64
      }
    
      var rawWeather = []byte(`[{"name":"London","cod":200,"dt":1407100800,"id":2643743}]`)
      var w []Weather
      err := json.Unmarshal(rawWeather, &w)
      if err != nil {
        fmt.Println("Some error", err)
      }
      fmt.Printf("%+v
    ",w)
    }
    

    So, the struct field names have to be Capitalized to work properly!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥200 关于#c++#的问题,请各位专家解答!
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀