我有一个带有动态键的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"`
}
答案 0 :(得分:0)
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)
}
}