-2

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": ""
    }
]
3
  • 3
    ` HostList {}Host` is not valid Go. It won't compile. Is that a typo? Commented Jun 11, 2019 at 17:12
  • 2
    What have you tried? What issue did you run into? Please show your attempt and describe specifically what problems you had. This seems fairly straightforward, aside from the typo where {}Host should be []Host. Commented Jun 11, 2019 at 17:12
  • You can just create a slice of Hosts, i.e. hostsSlice := []Host and then unmarshal your json into that hostsSlice variable for easy management. Sample playground code here Commented Jun 11, 2019 at 17:18

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.