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 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀