从 Go 中的 json 文件中读取多个 json 对象



我正在尝试从json文件中读取以下json对象。因此,对象的数量不是预定义的,它们可以是多个或只有一个。

所以我尝试制作这个结构,但我无法正确阅读它。我想解析 json 对象中的元素。

type HostList struct {
    HostList {}Host
}
type Host struct {
    IP       string `json: "ip"`
    Netmask  string `json: "netmask"`
    Gateway  string `json: "gateway"`
    Mac      string `json: "mac"`
    Hostname string `json: "hostname"`
    Callback string `json: "callback"`
}

我想阅读这个 Json 文件:

[
    {
        "ip": "4.3.2.10",
        "netmask": "255.255.255.234",
        "gateway": "4.3.2.1",
        "mac": "12:34:af:56:54:jj",
        "hostname": "cds1.yyy.com",
        "callback": ""
    },
    {
        "ip": "4.3.2.11",
        "netmask": "255.255.255.234",
        "gateway": "4.3.2.1",
        "mac": "12:34:af:55:54:jj",
        "hostname": "cds2.yyy.com",
        "callback": ""
    }
]

尝试使用下面

type HostList []struct {
  IP       string `json:"ip"`
  Netmask  string `json:"netmask"`
  Gateway  string `json:"gateway"`
  Mac      string `json:"mac"`
  Hostname string `json:"hostname"`
  Callback string `json:"callback"`
}

您可以使用此站点 https://mholt.github.io/json-to-go/从 JSON 生成 Go 结构。

最新更新