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 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 哪个tomcat中startup一直一闪而过 找不出问题
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码