doujiu3097 2017-04-17 02:12
浏览 84
已采纳

为什么struct字段的格式字符串总是小写

When encoding/decoding structs with json, almost all of the code out there use the same field name, but with the initial letter in lower case, why is this?

Since the names are the same, and json certainly can work with any case, why add this duplicate thing:

Name string `json:"name"`

Why not just use Name string? It other case, adding the format string makes sense if the name is different than the go field name:

Name string `json:"MyName"`
  • 写回答

3条回答 默认 最新

  • doutui6241 2017-04-17 02:17
    关注

    The encoding/json documentation says:

    The encoding of each struct field can be customized by the format string stored under the "json" key in the struct field's tag. The format string gives the name of the field, possibly followed by a comma-separated list of options. The name may be empty in order to specify options without overriding the default field name.

    Applications specify a lowercase name in the tag to produce a lowercase name in the JSON.

    This struct

    type Example struct {
      Name1 string
      Name2 string `json:"name1"`
    }
    

    encodes as:

    {
      "Name1": "1",
      "name1": "2"
    }
    

    playground example

    JSON only requires that field names be valid strings. Lowercase names are not required in JSON. That said, it is very common practice to start field names with a lowercase letter in JSON.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?