在 Go 中使用带有 API 调用的结构

Using struct with API call in Go

我是 Go 的新手,正在努力遵循它的风格,但我不确定如何继续。

我想将 JSON 对象推送到 Geckoboard leaderboard, which I believe requires the following format based on the API doc 并且专门用于排行榜:

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

我的直觉是为 API 调用自身构建一个 struct,另一个调用 Contestants,它将嵌套在 item 下。为了使用 json.Marshall(Contestant1),我的变量命名约定不符合 fmt 的期望:

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

这感觉不对。我应该如何配置我的 Contestant 对象并能够在不违反约定的情况下将它们编组到 JSON 中?

要从结构中输出正确的 JSON 对象,您必须导出该结构的字段。为此,只需将字段的第一个字母大写即可。

然后您可以添加某种注释,告诉您的程序如何命名您的 JSON 字段:

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