【发布时间】:2015-09-27 07:09:57
【问题描述】:
我从客户端 API 收到下面的 JSON,但我很难获得嵌套的 JSON 内容。如果内部键是动态的,我该如何解析它?
const jsonStream = `
{
"items": {
"bvu62fu6dq": {
"name": "john",
"age": 23,
"xyz": "weu33s"
},
"iaxdw23fq": {
"name": "kelly",
"age": 21,
"xyz": "weu33s"
}
}
}`
这是我在下面通过循环映射以从上面的 JSON 字符串中提取姓名和年龄的值来尝试的;但它返回值为零的地图作为结果。 goplaygound
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
type Item struct {
Contact struct {
Info map[string]Person
} `json:"items"`
}
func main() {
dec := json.NewDecoder(strings.NewReader(jsonStream))
for {
var item Item
if err := dec.Decode(&item); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", item.Contact.Info["bvu62fu6dq"].Name)
}
}
【问题讨论】:
-
你能编辑你的问题来解释唯一键的意义吗?仅在标题中提及
-
如果你这么说会更容易,而且你需要以什么形式获得。