Search code examples
jsongomarshalling

Add keys before json.Marshal in Golang


I am creating a function to get array of object and save it into Struct. Then I want to convert it into JSON.

func GetCountry(msg string) []byte {
    var countries []*countryModel.Country

    countries = countryModel.GetAllCountry()

    jsResult, err := json.Marshal(countries)

    if err != nil {
        logger.Error(err, "Failed on GetCountry")
    }

    return jsResult
}

Here is the struct

type Country struct {
    Id           int    `json:"id"`
    CountryCode string `json:"country_code"`
    CountryName string `json:"country_name"`
    PhoneCode   string `json:"phone_code"`
    Icon         string `json:"icon"`
}

With that function, i get these result

[
  {
    "id": 2,
    "country_code": "MY",
    "country_name": "Malaysia",
    "phone_code": "+60",
    "icon": "no-data"
  },
  {
    "id": 2,
    "country_code": "MY",
    "country_name": "Malaysia",
    "phone_code": "+60",
    "icon": "no-data"
  }
]

How can i add a key named 'countries' for that JSON result? These what i am expect

{
    "countries" : 
        [
          {
            "id": 2,
            "country_code": "MY",
            "country_name": "Malaysia",
            "phone_code": "+60",
            "icon": "no-data"
          },
          {
            "id": 2,
            "country_code": "MY",
            "country_name": "Malaysia",
            "phone_code": "+60",
            "icon": "no-data"
          }
        ]
}

Please help


Solution

  • You could create a wrapper struct that contains an array of country structs, with json: "countries" after the declaration for the countries array, then call json.Marshal on the wrapper.

    What it looks like:

    type CountryWrapper struct {
      Countries []*countryModel.Country `json: "countries"`
    } 
    

    Then, in your method, instantiate as CountryWrapper{ Countries: countries }, and call json.Marshal on this object.