How can I parse this json object:
{
"ports": {
"0": {
"3306": "3306"
},
"1": {
"3307": "9908"
}
}
}
I can have N ports, and the values for each port will always be a key:value pair.
So far I've tried this:
type Ports struct {
Port map[string]string
}
With this I get the keys (0, 1) but the values are empty.
I also tried this:
type Ports struct {
Port map[string]struct{
Values map[string]string
}
}
But also not working.
This is how I am decoding the json object:
var requestBody Ports
decoder := json.NewDecoder(body)
err := decoder.Decode(&requestBody)
Use this type:
type Ports struct {
Ports map[string]map[string]string
}
Notes:
You can parse it like this.
https://play.golang.org/p/09VDJidAVs
type Ports struct {
Ports map[string]*Port `json:"ports"`
}
type Port map[string]string
func main() {
p := &Ports{}
err := json.Unmarshal([]byte(ports),p)
if err != nil {
fmt.Println(err)
return
}
// using
// if you need to sort by the number value, get the keys in a slice
keys := make([]string, 0, len(p.Ports))
for k, _ := range p.Ports {
keys = append(keys, k)
}
// sort here
for i := range keys {
fmt.Printf("%+v
",p.Ports[keys[i]])
}
// if you don't care to sort
for _, v := range p.Ports {
for k, v := range *v {
fmt.Printf("%s: %s
", k,v)
}
}
}