jsongogo-structtag

Read Multiple json object from a json file in Go


I am trying to read the following json objects from the json file. So the number of objects are not predefined, they can be multiple or just one.

So I tried making this struct but I am not able to read it properly. I want to parse the elements inside the json object.

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"`
}

And I want to read this Json file:

[
    {
        "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": ""
    }
]

Solution

  • Try using below

    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"`
    }
    

    You can use this site https://mholt.github.io/json-to-go/ for generating Go struct from JSON.