json - golang json迭代不支持索引

标签 json go

我在 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_postsresponse->blog->name

这是一个指向 playground 的链接 感谢您的帮助!

最佳答案

您是否有理由要使用 map ?要使用 map 进行您正在谈论的索引,我认为您还需要嵌套 map

您是否考虑过使用嵌套结构,如此处所述,Go Unmarshal nested JSON structureUnmarshaling 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 中,structsliceobjectarray[{. .},{..}]

在 Go 中,只有导出的字段才会被填充。

关于json - golang json迭代不支持索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41748478/

相关文章:

javascript - JSON 损坏的属性

android - 如何根据其他微调器选择过滤微调器?

java - 将多态 json 序列化为特定的 jsonnode

javascript - 从嵌套的 json 中排序的 Angular 4 数据表

go - 同时来自列表的多个随机元素

java - Jackson 对特定属性使用 getter

go - 为 GOOGLE_APPLICATION_CREDENTIALS 设置凭据的替代方法

Golang panic 崩溃预防

go - 有没有办法从 https ://www. 重定向。到 https ://. 。在围棋?

postgresql - Postgres 返回 []uint8 而不是 []integer