doudeng9425 2015-10-28 18:38
浏览 39
已采纳

在Go中将struct与API调用结合使用

I'm new to Go and working hard to follow its style and I'm not sure how to proceed.

I want to push a JSON object to a Geckoboard leaderboard, which I believe requires the following format based on the API doc and the one for leaderboards specifically:

{
  "api_key": "222f66ab58130a8ece8ccd7be57f12e2",
  "data": {
     "item": [
        { "label": "Bob", "value": 4, "previous_value": 6 },
        { "label": "Alice", "value": 3, "previous_value": 4 }
      ]
  }
}

My instinct is to build a struct for the API call itself and another called Contestants, which will be nested under item. In order to use json.Marshall(Contestant1), the naming convention of my variables would not meet fmt's expectations:

// Contestant structure to nest into the API call
type Contestant struct {
    label  string
    value int8
    previous_rank int8  
}

This feels incorrect. How should I configure my Contestant objects and be able to marshall them into JSON without breaking convention?

  • 写回答

1条回答 默认 最新

  • dongzhan1570 2015-10-28 18:46
    关注

    To output a proper JSON object from a structure, you have to export the fields of this structure. To do it, just capitalize the first letter of the field.

    Then you can add some kind of annotations, to tell your program how to name your JSON fields :

    type Contestant struct {
        Label  string `json:"label"`
        Value int8 `json:"value"`
        PreviousRank int8 `json:"previous_rank"` 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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