dqtdz08206 2017-05-16 21:29
浏览 91
已采纳

解析动态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)
  • 写回答

2条回答 默认 最新

  • duancenxiao0482 2017-05-16 21:37
    关注

    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).
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?