json - 来自 json 响应的结构

标签 json go

我有一个带有动态键的 json 响应,我在将它解码为一个结构时遇到了一些困难。有人可以协助结构吗?

{
    "accountDetails": {
        "123": {
            "userDetails": {
                "login": 123
            }
        },
        "456": {
            "userDetails": {
                "login": 456
            }
        }
    }
}

目前我的结构是:

type Response struct {
    AccountDetails AccountDetails `json:"accountDetails"`
}

type AccountDetails struct {
    Accounts map[string]UserDetails
}

type UserDetails struct {
    Account Account `json:"userDetails"`
}

type Account struct {
   Login int `json:"login"`
}

最佳答案

var data = []byte(`{
    "accountDetails": {
        "123": {
            "userDetails": {
                "login": 123
            }
        },
        "456": {
            "userDetails": {
                "login": 456
            }
        }
    }
}`)

type Response struct {
    AccDetails map[string]AccountDetails `json:"accountDetails"`
}

type AccountDetails struct {
    UserDetails struct {
        Login int `json:"login"`
    } `json:"userDetails"`
}

func main() {
    var resp Response
    if err := json.Unmarshal(data, &resp); err != nil {
        fmt.Fprintf(os.Stderr, "json err: %v", err)
        os.Exit(1)
    }
    fmt.Printf("%T\n", resp.AccDetails)
    for user, userDet := range resp.AccDetails {
        fmt.Println(user, userDet.UserDetails.Login)
    }
}

关于json - 来自 json 响应的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55759115/

相关文章:

Golang OpenSSL 错误的 iv 大小

C++ REST SDK (Casablanca) web::json 迭代

javascript - 如何使用 jQuery 或 JavaScript 重复 div?

javascript - 从 Ajax 响应中摘录

php - json转mysql。我如何将 json 对象转换为 sql 查询?

c# - 反序列化 MandrillApp Webhook 响应

go - 如何将值列表放入 Golang 中的标志中?

regex - 去正则表达式不匹配

go - 如何使用 gocc 在 Golang 中实现不区分大小写的词法解析器?

go - 在golang中ec2.CreateSecurityGroup中的名称类型是什么