英文:
Add keys before json.Marshal in Golang
问题
你可以通过创建一个包含"countries"键的map,将原始的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")
}
// 创建一个包含"countries"键的map
result := map[string]interface{}{
"countries": jsResult,
}
// 将map转换为JSON格式
finalResult, err := json.Marshal(result)
if err != nil {
logger.Error(err, "Failed to marshal final result")
}
return finalResult
}
这样,你将得到一个包含"countries"键的JSON结果。希望对你有帮助!
英文:
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
答案1
得分: 1
你可以创建一个包含国家结构体数组的包装结构体,声明国家数组后加上 json: "countries"
,然后对该包装结构体调用 json.Marshal。
代码示例:
type CountryWrapper struct {
Countries []*countryModel.Country `json:"countries"`
}
func YourMethod() {
// 假设你已经有了一个名为 countries 的国家数组
wrapper := CountryWrapper{Countries: countries}
jsonData, err := json.Marshal(wrapper)
if err != nil {
// 错误处理
}
// 处理 jsonData
}
这样,你就可以将国家数组转换为 JSON 数据了。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论