Using struct with API call in Go

huangapple go评论91阅读模式
英文:

Using struct with API call in Go

问题

我是你的中文翻译助手,以下是翻译好的内容:

我刚开始学习Go语言,努力遵循其编码风格,但我不确定该如何继续。

我想要将一个JSON对象推送到Geckoboard排行榜,根据API文档和排行榜的文档,我相信需要按照以下格式:

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

我的直觉是为API调用本身构建一个struct,并在item下面嵌套一个名为Contestants的结构。为了使用json.Marshal(Contestant1),我的变量命名规范可能不符合fmt的期望:

// 嵌套在API调用中的Contestant结构
type Contestant struct {
    label  string
    value int8
    previous_rank int8  
}

这种方式感觉不正确。我应该如何配置我的Contestant对象,并能够将它们编组成JSON而不违反约定?

英文:

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

得分: 3

要从结构体中输出一个正确的JSON对象,你需要导出该结构体的字段。为此,只需将字段的首字母大写。

然后,你可以添加一些注释,告诉你的程序如何命名JSON字段:

type Contestant struct {
    Label         string `json:"label"`
    Value         int8   `json:"value"`
    PreviousRank  int8   `json:"previous_rank"`
}

以上是你要翻译的内容。

英文:

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"` 
}

huangapple
  • 本文由 发表于 2015年10月29日 02:38:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/33399035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定