dongxiane0395 2018-07-28 11:49
浏览 60
已采纳

通过解码go中的JSON文件来创建结构数组

All I looking to do is to create an array of struct Response from a json encoded file.

the file that contains json data looks like this.

cat init.txt

{"events": [{"action":"cpr","id":69,"sha1":"abc","cpr":"cpr_data0"},{"action":"cpr","id":85,"sha1":"def","cpr":"cpr_data1"}]}

The way I have gone about approaching this is

  • I created a response of type map[string][]Response

  • .. decoded the JSON from the file

  • .. created a responseStruct of type []Response

But somehow when I inspect the Value they all look 0 or empty

map[events:[{ 0 } { 0 }]

What is wrong with the approach mentioned above.

type Response struct {
  action string `json:"action"`
  id     int64  `json:"id"`
  sha1   string `json:"sha1"`
  cpr    string `json:"cpr"`
}

func main() {
  file, err := os.Open("init.txt")
  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }
  var response map[string][]Response
  err = json.NewDecoder(file).Decode(&response)
  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }

  var responseArray []Response
  responseArray = response["events"]
  for _, responseStruct := range responseArray {
    fmt.Println("id =", responseStruct.id)
    fmt.Println("action =", responseStruct.action)
    fmt.Println("sha1 = ", responseStruct.sha1)
    fmt.Println("cpr =", responseStruct.cpr)
    fmt.Println("==========")
  }
  fmt.Println(response)
}

Well If I modify the struct to look like this it works

type Response struct {
  Action string `json:"action"`
  ID     int64  `json:"id"`
  Sha1   string `json:"sha1"`
  Cpr    string `json:"cpr"`
}

So my question is this how the stuff would work, can't I get the above code to work in the way it is?

  • 写回答

2条回答 默认 最新

  • dsideal2015 2018-07-28 12:20
    关注

    Go has the notion of public and private fields in objects, and the only distinction is whether they start with an initial capital letter or not. This applies to not just code modules but also the reflect package and things that use it. So in your initial version

    type Response struct {
      action string `json:"action"`
      ...
    }
    

    nothing outside your source package, not even the "encoding/json" module, can see the private fields, so it can't fill them in. Changing these to public fields by capitalizing Action and the other field names makes them visible to the JSON decoder.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器