{
"devices": [
{
"id": 20081691,
"targetIp": "10.1.1.1",
"iops": "0.25 IOPS per GB",
"capacity": 20,
"allowedVirtualGuests": [
{
"Name": "akhil1"
},
{
"Name": "akhil2"
}
]
}
]
}
How to write a structure representation of this JSON data so that I can add and delete devices to the list. I tried with the different structure representations but nothing is working. Below is one of the example I have tried with a similar kind of json data. I am not able to add new data to it. The structure representation and the way the append is done might be wrong here
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
ID string `json:"id,omitempty"`
Firstname string `json:"firstname,omitempty"`
Lastname string `json:"lastname,omitempty"`
Address []Address `json:"address,omitempty"`
}
type Address[] struct {
City string `json:"city,omitempty"`
}
func main() {
var people []Person
people = append(people, Person{ID: "1", Firstname: "Nic", Lastname: "Raboy", Address: []Address{{City: "Dublin"},{ City: "CA"}}} )
b, err := json.Marshal(people)
if err != nil {
fmt.Println("json err:", err)
}
fmt.Println(string(b))
}
It will be below. This was generated using the excellent JSON-to-GO tool:
type MyStruct struct {
Devices []struct {
ID int `json:"id"`
TargetIP string `json:"targetIp"`
Iops string `json:"iops"`
Capacity int `json:"capacity"`
AllowedVirtualGuests []struct {
Name string `json:"Name"`
} `json:"allowedVirtualGuests"`
} `json:"devices"`
}
To simplify that though, you can break it into smaller structs for readability. An example is below:
package main
import "fmt"
type VirtualGuest struct {
Name string `json:"Name"`
}
type Device struct {
ID int `json:"id"`
TargetIP string `json:"targetIp"`
Iops string `json:"iops"`
Capacity int `json:"capacity"`
AllowedVirtualGuests []VirtualGuest `json:"allowedVirtualGuests"`
}
type MyStruct struct {
Devices []Device `json:"devices"`
}
func main() {
var myStruct MyStruct
// Add a MyStruct
myStruct.Devices = append(myStruct.Devices, Device{
ID:1,
TargetIP:"1.2.3.4",
Iops:"iops",
Capacity:1,
AllowedVirtualGuests:[]VirtualGuest{
VirtualGuest{
Name:"guest 1",
},
VirtualGuest{
Name:"guest 2",
},
},
})
fmt.Printf("MyStruct: %v
", myStruct)
}
you can use struct tag like json:"id"
, try struct below:
type Data struct {
Devices []struct {
Id int `json:"id"`
IP string `json:"targetIp"`
IOPS string `json:"iops"`
Capacity int `json:"capacity"`
AllowedVirtualGuests []struct {
Name string `json:"Name"`
} `json:"allowedVirtualGuests"`
} `json:"devices"`
}