golang json迭代不支持索引

I've got a problem with my json parsing in golang. I used some code to parse the json into a map[string]interface{}{} but when I try to iterate through a nested field, the error (type interface {} does not support indexing) is triggered.

I'd like to get the following informations :

  • iterate through each response->blogs and then get the url of original_size photo that lays in response->posts->blog_n->photos->original_size
  • meta->status
  • response->blog->total_posts and response->blog->name

Here's a link to a playground Thank you for your help !

Is there a reason you want to use a map? To do the indexing you're talking about, with maps, I think you would need nested maps as well.

Have you considered using nested structs, as described here, Go Unmarshal nested JSON structure and Unmarshaling nested JSON objects in Golang ?

For your JSON data, here is a sample -- working but limited -- struct. Go will ignore the fields you don't use.

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
", m)
}
type Header struct {
    Response struct { 
        Blog struct {
            Title string `json:"title"`
        } `json:"blog"`
        Posts []struct {
            Id int64 `json:"id"`
        } `json:"posts"`
    } `json:"response"`
}

To get JSON with Go to do what you want, you have to brush up on JSON and it's relation to Go types.

Notice posts: slices of structs are, in JSON, arrays of objects, [{..},{..}]

In Go, only exported fields will be filled.

this error appear because your map[key-type]val-type, and you to try get value as nested map.

you can use Type Assertion to get value.

result := m["response"].(map[string]interface{}) 
fmt.Printf("%+v
", result["blog"])