0

here is my problem which I am confronted with. I am currently taking the data from an API with its format (I can't change it like that). So I have created a new structure to take the data and to change just the titles (in my case: it would be to change "name" by "nickname". But problem is that I block in my for loop to replace name by nickname. If you have any questions or solutions to give, I'm welcome ;)

My structure (from ItemsResponse to Tools : this is the format requested by the API and the champion structure corresponds to the change I want to make on my own api

type ItemsResponse struct {
    Items []Brawler `json:"items"`
}

type Brawler struct {
    ID         int      `json:"id"`
    Username   string   `json:"Name"`
    StarPowers []Powers `json:"starPowers"`
    Gadgets    []Tools  `json:"gadgets"`
}

type Powers struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

type Tools struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

type Champion struct {
    Id       int    `json:"id"`
    NickName string `json:"nickname"`
}

My function to get the data from the api :

func getChampions(w http.ResponseWriter, r *http.Request) {

    // get response from external API through resty library
    client := resty.New()
    var items ItemsResponse

    resp, err := client.R().
        SetHeader("Authorization", "application/json").
        SetAuthToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6IjljYWJlNjNiLWI4ZTQtNGZjNy1iMTBlLWVhMTExOTBmMGJkZSIsImlhdCI6MTY1NTcxMzcyMiwic3ViIjoiZGV2ZWxvcGVyL2M3OTZmM2MxLTE4ZTktNjE0YS0wY2M3LWMwMWIyNTQ2ZDViYiIsInNjb3BlcyI6WyJicmF3bHN0YXJzIl0sImxpbWl0cyI6W3sidGllciI6ImRldmVsb3Blci9zaWx2ZXIiLCJ0eXBlIjoidGhyb3R0bGluZyJ9LHsiY2lkcnMiOlsiMTc4LjIwLjUwLjIwOSJdLCJ0eXBlIjoiY2xpZW50In1dfQ.pbdssmUbaGtoUTKgNOPmspo2gOdtZt7wrgQj3JA1xP8StdKlsg0tAz1iDygAjupUuhjE7ZoHDctNI05vJgwlsw").
        Get("https://api.brawlstars.com/v1/brawlers")

    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }

    // unmarshall struct
    json.Unmarshal(resp.Body(), &items)
    fmt.Println(items)

    //sort items
    champions := sortBrawler(items.Items)

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(items)
}

My function with the for loop or I am stuck :

func sortBrawler(brawlers []Brawler) []Champion {
    var champions []Champion
    // for each brawler we create a champion with the same name as nickname and add it
    // to the champions lists
    for i := range brawlers {
        // create a champion
        var champ Champion
        // add a champion to champions array
        champions = append(champions, champ)
    }
    return champions
}

Result of what I get (without making any changes just by respecting their format) :

{
    "items": [
        {
            "id": 16000000,
            "Name": "SHELLY",
            "starPowers": [
                {
                    "id": 23000076,
                    "name": "SHELL SHOCK"
                },
                {
                    "id": 23000135,
                    "name": "BAND-AID"
                }
            ],
            "gadgets": [
                {
                    "id": 23000255,
                    "name": "FAST FORWARD"
                },
                {
                    "id": 23000288,
                    "name": "CLAY PIGEONS"
                }
            ]
        },
Eloi Jahan
  • 39
  • 6
  • It looks like you're trying to convert one struct to another struct type, to control the json tags. It's fairly common when you read from one API and send on to another one, or another process. One option is to convert the type, as shown here: https://stackoverflow.com/a/24613420/6031948 . In your case for the loop, the field names don't match. So you must do something explicit like `c := Champion{Id: brawler[i].ID, NickName: brawler[i].Username}` – Brian Wagner Jun 22 '22 at 13:22
  • Like this ? @BrianWagner `champions = append(champions, newChamp, Champion{Id: brawlers[i].ID,NickName:brawlers[i].Username,})` If it works how do I launch the new result and not stay on the old one? – Eloi Jahan Jun 22 '22 at 13:37
  • I think the first comment from blackgreen above addresses that. You pass `champions` not `items` to `Encode()` – Brian Wagner Jun 22 '22 at 13:49

0 Answers0