【问题标题】:Go return json variables without capitals [duplicate]去返回没有大写的json变量[重复]
【发布时间】:2018-06-01 00:52:06
【问题描述】:

我是将应用程序转换为 Go 的新用户。我有类似以下的工作:

type Network struct {
        Ssid     string
        Security string
        Bitrate  string
}

func Scan(w http.ResponseWriter, r *http.Request) {
        output := runcmd(scripts+"scan.sh", true)
        bytes := []byte(output)
        var networks []Network
        json.Unmarshal(bytes, &networks)
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(networks)
}

问题是旧版本没有在返回的 json 变量上使用大写字母。

我希望前端看到ssid 而不是Ssid。如果我将结构中的属性设为小写,则代码将不再有效,因为它们会变成未导出的变量。

【问题讨论】:

    标签: json go


    【解决方案1】:

    当你的 struct 中的字段名与 json 字段名不匹配时,你可以使用字段标签。 例如:

    Ssid string `json:"myOtherFieldName"`
    

    请阅读json docs了解更多详情。

    【讨论】:

      【解决方案2】:

      这个工具学习起来很方便:

      https://mholt.github.io/json-to-go/

      给它一个你想要的 JSON 示例,它会推荐 golang。

      例如JSON

      {
         "ssid": "some very long ssid",
         "security": "big secret",
         "bitrate": 1024
      }
      

      会推荐golang:

      type AutoGenerated struct {
          Ssid     string `json:"ssid"`
          Security string `json:"security"`
          Bitrate  int    `json:"bitrate"`
      }
      

      现在您可以将AutogGenerated, Ssid, Security, Bitrate 更改为您想要的任何内容。

      【讨论】:

        猜你喜欢
        • 2019-09-02
        • 1970-01-01
        • 2016-09-22
        • 1970-01-01
        • 2014-10-02
        • 1970-01-01
        • 2017-09-04
        • 2017-03-09
        • 2021-12-18
        相关资源
        最近更新 更多