在 Golang json.Marshal 之前添加键

Add keys before json.Marshal in Golang

我正在创建一个函数来获取对象数组并将其保存到 Struct 中。然后我想把它转换成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
}

这是结构

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"`
}

有了这个功能,我得到了这些结果

[
  {
    "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"
  }
]

如何为 JSON 结果添加一个名为 'countries' 的键?这些是我所期待的

{
    "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"
          }
        ]
}

请帮忙

您可以创建一个包含国家/地区结构数组的包装器结构,在国家/地区数组声明之后使用 json: "countries",然后在包装器上调用 json.Marshal。

外观:

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

然后,在您的方法中,实例化为 CountryWrapper{ Countries: countries },并在此对象上调用 json.Marshal。