返回没有大写的json变量[重复]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

我是一个将应用程序转换为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
2个回答
4
投票

如果结构中的字段名称与json字段名称不匹配,则可以使用字段标记。例如:

Ssid string `json:"myOtherFieldName"`

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


1
投票

这个工具非常方便学习:

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

给它你希望它推荐golang的JSON示例。

如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改为你想要的任何东西。

© www.soinside.com 2019 - 2024. All rights reserved.