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

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料