1

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 !

gmolveau
  • 95
  • 1
  • 12

2 Answers2

3

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\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"`
}

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.

Community
  • 1
  • 1
Nevermore
  • 7,141
  • 5
  • 42
  • 64
  • Thank you for your answer ! nope, no reason I just found this piece of code. Would you be able to provide me the complete struct please ? – gmolveau Jan 19 '17 at 18:39
  • @gmolveau the complete struct would be pretty large, because the json is pretty big. I'm not really sure what you need, but I thing you could modify the code I provided to get you there :) cheers – Nevermore Jan 19 '17 at 18:48
  • Thank you for your answer :D – gmolveau Jan 19 '17 at 19:02
  • @gmolveau sure! I'm glad it helps, and if it's the solution, then could you mark it as correct? (the green check mark) :) – Nevermore Jan 19 '17 at 19:03
  • I'm indeed going to go with your solution ! :) – gmolveau Jan 19 '17 at 19:07
1

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\n", result["blog"])
M-AbdalRahman
  • 251
  • 3
  • 11