Ratatouille
Ratatouille

Reputation: 1462

Avoid typecasting a slice value in loop

I'm reading an API (JSON) response from a server and I'm supposed to get(if the status is 200 ok) the following responses back.

// If I sent a wrong data ..
{ 
  error: "some value",
  message: "... description of the error"
}

or

// if all is good 
{
  events: [{key1: 1}, {key2: "two"} ... ]
}

because I'm not sure about the type of response. I'm decoding the response as a map[string]interface{}.

resp := make(map[string]interface{}, 0)
json.NewDecoder(response.Body).Decode(&resp)

Later in the code flows I reach a stage where I know that response is an all good one. I need to typecast the interface{} back to []map[string]interface{}.

but I think this does not work ..

// This does not work I guess. 
// events := resp["events"].([]map[string]interface{})

The only sane way I manage to do this is using.

interFace := resp["events"].([]interface{})
for mapInterface := range interFace {
  row := MapInterface.(map[string]interface{})
  // now use the row hence forth
} 

Can this be done in any other way or any Other approach1 that would avoid the casting in inside the loop.

1: Maybe creating a Response struct over here can work. But I would really like to hear any other approaches that I can try before forward with a struct approach.

Upvotes: 0

Views: 42

Answers (1)

jmaloney
jmaloney

Reputation: 12300

You could define a struct that has both the error values and non error values in your struct.

type Response struct {
    ErrorMessage string `json:"message"`
    Error string `json:"error"`
    Events []map[string]interface{} `json:"events"`
}

Upvotes: 1

Related Questions