解析动态json对象

人气:553 发布:2022-10-16 标签: json go

问题描述

如何解析此json对象:

How can I parse this json object:

{
    "ports": {
        "0": {
            "3306": "3306"
        },
        "1": {
            "3307": "9908"
        }
    }
}

我可以有N个端口,每个端口的值始终是key:value对.

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
}

这样我得到了键(0、1),但是值是空的.

With this I get the keys (0, 1) but the values are empty.

我也尝试过:

type Ports struct {
    Port map[string]struct{
        Values map[string]string
    }
}

但也不起作用.

这就是我解码json对象的方式:

This is how I am decoding the json object:

var requestBody Ports
decoder := json.NewDecoder(body)
err := decoder.Decode(&requestBody)

推荐答案

使用此类型:

type Ports struct {
    Ports map[string]map[string]string
}

游乐场示例

注意:

字段名称非常匹配.我使用字段名称端口"来匹配JSON文本中使用的名称. Go类型在JSON中应具有相同级别的嵌套.一个结构和映射每个计数用于一个嵌套级别.第一次尝试没有足够的嵌套,第二次尝试具有太多的嵌套级别(带有值"字段的结构).

301