解析动态json对象

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
}

playground example

Notes:

  • The field names much match. I used field name "Ports" to match the name used in the JSON text.
  • The Go types should have the same level of nesting in the JSON. A struct and map each count for one level of nesting. The first attempt does not have enough nesting, the second attempt has one too many levels of nesting (the struct with Values field).

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)
        }
    }
}