Convert string in struct to []string


I have a struct as below:

type TourData struct {
    ArtistID   int    //artist ID
    RelationID string //key for relations
    City       string
    Country    string
    TourDates  []string

type MyRelation struct {
    ID             int                 `json:"id"`
    DatesLocations map[string][]string `json:"datesLocations"`

which contains this data from a csv file:

2,playa_del_carmen-mexico,Playa Del Carmen,Mexico,

MyRelations is populated from an API which contains:

"index": [
            "id": 1,
            "datesLocations": {
                "dunedin-new_zealand": [
                "nagoya-japan": [
                "penrose-new_zealand": [
            "id": 2,
            "datesLocations": {
                "papeete-french_polynesia": [
                "playa_del_carmen-mexico": [

The dates come from another struct. The code I have used to populate this struct is as below:

var oneRecord TourData
    var allRecords []TourData

for _, each := range csvData {
    oneRecord.ArtistID, _ = strconv.Atoi(each[0])
    oneRecord.RelationID = each[1]
    oneRecord.City = each[2]
    oneRecord.Country = each[3]
    oneRecord.TourDates = Relations.Index[oneRecord.ArtistID-1].DatesLocations[each[1]]
    allRecords = append(allRecords, oneRecord)
jsondata, err := json.Marshal(allRecords) // convert to JSON
json.Unmarshal(jsondata, &TourThings)

I need to group all the 1s together then the 2s etc. I thought to create another struct, and populate from this one but not having much luck – any ideas?

To clarify I would want say TourData.City to equal:

[Playa Del Carmen, Papeete]

At the moment if I was to print TourData[0].City I would get Nagoya.

I have tried creating another struct to be populated from the TourData struct with the following fields:

type TourDataArrays struct {
    ArtistID  int
    City      []string
    Country   []string
    TourDates [][]string

and then populate the struct using the code below:

var tourRecord TourDataArrays
    var tourRecords []TourDataArrays
    for i := 0; i < len(Relations.Index); i++ {
        for j := 0; j < len(allRecords); j++ {
            if allRecords[i].ArtistID == i+1 {
                tourRecord.City = append(tourRecord.City, allRecords[j].City)
        tourRecords = append(tourRecords, tourRecord)

However this is adding all the cities to one array i.e

[Nagoya, Penrose, Dunedin, Playa Del Carmen, Papeete].


If I understand your requirements correctly you needed to declare city as a string array as well. (And Country to go with it).

Check out this solution :

Note I have not deduped country and derived city and country from one field in the Json.

Answered By – Shakthi Thillai

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.