在Go中使用带有API调用的struct

时间:2015-10-28 18:38:10

标签: json go coding-style

我是Go的新手,并努力遵循其风格,我不知道如何继续。

我想将JSON对象推送到Geckoboard leaderboard,我认为这需要基于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?

1 个答案:

答案 0 :(得分:3)

要从结构输出正确的JSON对象,您必须导出此结构的字段。要做到这一点,只需将字段的第一个字母大写。

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

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