How do I unMarshal this json code in Golang. I have the hostname and ipaddress but not the snmpV1 part:

[
    {
        "hostname" : "myserver",
        "ipaddress" : "127.0.0.1",
        "snmpVersion" : 1,
        "snmpV1" : {
            "community" : "public"
        }
    }
]

I have the following struct:

type Device struct {
    Hostname string `json: "hostname"`
    Ipaddress string `json:"ipaddress"`
    SnmpVersion int `json:"snmpVersion"`
    SnmpV1cred struct {
        Community string `json: "community"`
    } `json: "snmpV1"`
    SnmpV3cred struct {
        secName string `json: "secName"`
        authPassword string `json: "authPassword"`
        AuthProto string `json: "authProtocol"`
        PrivPassword string `json: "privPassword"`
        PrivProto string `json: "priveProtocol"`
        secLevel string `json: "secLevel"`
    } `json: "snmpV3"`
}

Then I unmarshal using:

deviceList := []Device{}
buffer, err := ioutil.ReadFile(deviceFile)
if err != nil {
    logger.Fatal(err)
}

err = json.Unmarshal(buffer, &deviceList)

However I only get this with a fmt.Println: [{myserver 127.0.0.1 1 {} { }}]

1 Answers

0
ThunderCat On Best Solutions

Remove spaces between : and " in field tags. Export all fields.

type Device struct {
    Hostname    string `json:"hostname"`
    Ipaddress   string `json:"ipaddress"`
    SnmpVersion int    `json:"snmpVersion"`
    SnmpV1cred  struct {
        Community string `json:"community"`
    } `json:"snmpV1"`
    SnmpV3cred struct {
        SecName      string `json:"secName"`
        AuthPassword string `json:"authPassword"`
        AuthProto    string `json:"authProtocol"`
        PrivPassword string `json:"privPassword"`
        PrivProto    string `json:"priveProtocol"`
        SecLevel     string `json:"secLevel"`
    } `json:"snmpV3"`
}

The go vet command reports these errors.