在Golang中,在json.Marshal之前添加键。

huangapple go评论69阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年3月21日 15:17:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/42920581.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定