When Unmarshalling data from an endpoint, I almost always have a struct with the data that I am want to get from my request that I unmarshal into. Well there are times where I want to see everything that is returning back to me but I am not sure what some of that data is so I don't know how to define it in my struct. Is there a way to have a struct that can just grab all data being unmarshalled without me having to specify it?
This is what I thought would work but that is not the case
resp, err := httpClient.Get("/api/stuff")
data, _ := ioutil.ReadAll(resp.Body)
var myStruct struct{}
json.Unmarshal(data, myStruct)
If you do not know the composition of a JSON object in advance, you can unmarshal into a map[string]interface{}
.
var myMap map[string]interface{}
json.Unmarshal(data, &myMap)
See an example here.
If you don't know how to define your struct, then maybe you should use a map. It's a pretty good fit for unmarshalling JSON. Here is an example of how to do it without knowing exactly what data you are receiving:
func parseJSON(r *http.Request) (map[string]interface{}, error) {
var postData interface{}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&postData)
if err != nil {
return nil, err
}
return postData.(map[string]interface{}), nil
}
Now you at least have a string name of each piece of data, which should give your application some idea of how to handle it.