How to map or make struct for variable json response in golang?

I am calling an API and getting json and don't know how to make a struct for the response I have used JSON-to-GO to get a struct for the response. But the problem is the response is not same every time. For example I have a struct using the JSON-to-GO :-

type Autogenerated struct {
    Response struct {
        Results struct {
            Status      string `json:"status"`
            StatusCode  int    `json:"status_code"`
            ResultsData struct {
                ResultsCount       int `json:"results_count"`
                NearbyCount int `json:"nearby_count"`
            } `json:"results_data"`
            SortData struct {
                SortBy string `json:"sort_by"`
            } `json:"sort_data"`
            ResponseData struct {
                Data0 struct {
                    Name string `json:"name"`
                } `json:"data_0"`
                Data1 struct {
                    Name string `json:"name"`
                } `json:"data_1"`
            } `json:"response_data"`
            Time float64 `json:"time"`
        } `json:"results"`
    } `json:"response"`
}

The Data1 and Data0 can be any more like Data2, Data3.... and I want the Name inside of the Data0, Data1 .... I am very new to golang, Maybe we can use Map for it but due to being not same all the time I don't know, how to do it. Also there are a lot of filed along with Name which I have not pasted here to keep the question clean.

1 answer

  • answered 2021-05-15 18:38 nipuna

    use map[string]interface{} for Response data type. Data0 to any number os Data0 type fields unmarshal to map as keys data_0, data_1, data_2

    ResponseData map[string]interface{} `json:"response_data"`
    

    If your Data coming as a same object for every data_0 ... data_n, then define struct type like below and define map with that type.

    //new data type
    type Data struct {
        Name string  `json:"name"`
    }
    
    //add this to your Autogenerated struct 
    ResponseData map[string]Data `json:"response_data"`
    

    or simply add

    ResponseData map[string]struct{
        Name string `json:"name"`
    } `json:"response_data"`