我在 golang 中解析 json 时遇到问题。
我使用一些代码将 json 解析为 map[string]interface{}{}
但是当我尝试遍历嵌套字段时,错误 (type interface {} does not support indexing)
被触发。
我想获得以下信息:
- 遍历每个
response->blogs
,然后获取放置在response->posts->blog_n->photos->original_size
中的original_size照片的url> meta->status
response->blog->total_posts
和response->blog->name
这是一个指向 playground 的链接 感谢您的帮助!
最佳答案
您是否有理由要使用 map
?要使用 map 进行您正在谈论的索引,我认为您还需要嵌套 map 。
您是否考虑过使用嵌套结构,如此处所述,Go Unmarshal nested JSON structure和 Unmarshaling nested JSON objects in Golang ?
对于您的 JSON 数据,这里有一个示例——有效但有限——struct
。 Go 将忽略您不使用的字段。
func main() {
//Creating the maps for JSON
data := &Header{}
//Parsing/Unmarshalling JSON encoding/json
err := json.Unmarshal([]byte(input), &data)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", m)
}
type Header struct {
Response struct {
Blog struct {
Title string `json:"title"`
} `json:"blog"`
Posts []struct {
Id int64 `json:"id"`
} `json:"posts"`
} `json:"response"`
}
要让 JSON 与 Go 一起做你想做的事,你必须复习 JSON 以及它与 Go 类型的关系。
公告帖:
在 JSON 中,struct
的 slice
是 object
的 array
,[{. .},{..}]
在 Go 中,只有导出的字段才会被填充。
关于json - golang json迭代不支持索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41748478/