移除字段名 id 并重新格式化 golang 中的 JSON 输出。

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

Removed fieldname id and reformat JSON Output in golang

问题

我正在使用基于 /v1/public/charactersMarvel API 开发一个使用 Golang 的 REST API。我需要以以下格式返回所有角色的 ID:

  1. [ 1011234, 1012345, 1009213, 1010788, 1087123, 1222345, ... ]

我通过使用 strings.NewReplacer 来实现这个目标(在下面的最后两行代码中)。

  1. ...
  2. type CharacterId struct {
  3. Data struct {
  4. Results []struct {
  5. Id int `json:"id"`
  6. } `json:"results"`
  7. } `json:"data"`
  8. }
  9. func getCharacters(w http.ResponseWriter, _ *http.Request) {
  10. ts := strconv.FormatInt(time.Now().Unix(), 10)
  11. hash := getMd5(ts + conf.privateKey + conf.publicKey)
  12. response, err := http.Get("https://gateway.marvel.com/v1/public/characters?ts=" + ts + "&apikey=" + conf.publicKey + "&hash=" + hash + "&limit=100")
  13. if err != nil {
  14. log.Fatal(err)
  15. }
  16. defer response.Body.Close()
  17. responseBytes, err := ioutil.ReadAll(response.Body)
  18. if err != nil {
  19. log.Fatal(err)
  20. }
  21. var characterId CharacterId
  22. err = json.Unmarshal(responseBytes, &characterId)
  23. if err != nil {
  24. log.Fatal(err)
  25. return
  26. }
  27. data, err := json.Marshal(characterId.Data.Results)
  28. replacer := strings.NewReplacer("\"id\":", "", "{", "", "}", "", ",", ", ", "[", "[ ")
  29. fmt.Fprint(w, replacer.Replace(string(data)))
  30. }

如果不使用像上面代码片段中的 strings.NewReplacer,即直接使用 fmt.Fprint(w, string(data)),会得到以下输出,这不是我想要的结果。

  1. [{"id":1011334},{"id":1017100},{"id":1009144},{"id":1010699},{"id":1009146},{"id":1016823},{"id":1009148},{"id":1009149}, ... ]

我有点觉得我使用 strings.NewReplacer 的方式不够干净/合适。有人能否提供一个更好的方法来得到我想要的输出?

英文:

I am developing a rest api using golang based on /v1/public/characters of Marvel API. I need to return all the character ids in the format of

  1. [ 1011234, 1012345, 1009213, 1010788, 1087123, 1222345, ... ]

The way I achieve this is via strings.NewReplacer (in last 2 lines below).

  1. ...
  2. type CharacterId struct {
  3. Data struct {
  4. Results []struct {
  5. Id int `json:"id"`
  6. } `json:"results"`
  7. } `json:"data"`
  8. }
  9. func getCharacters(w http.ResponseWriter, _ *http.Request) {
  10. ts := strconv.FormatInt(time.Now().Unix(), 10)
  11. hash := getMd5(ts + conf.privateKey + conf.publicKey)
  12. response, err := http.Get("https://gateway.marvel.com/v1/public/characters?ts=" + ts + "&apikey=" + conf.publicKey + "&hash=" + hash + "&limit=100")
  13. if err != nil {
  14. log.Fatal(err)
  15. }
  16. defer response.Body.Close()
  17. responseBytes, err := ioutil.ReadAll(response.Body)
  18. if err != nil {
  19. log.Fatal(err)
  20. }
  21. var characterId CharacterId
  22. err = json.Unmarshal(responseBytes, &characterId)
  23. if err != nil {
  24. log.Fatal(err)
  25. return
  26. }
  27. data, err := json.Marshal(characterId.Data.Results)
  28. replacer := strings.NewReplacer("\"id\":", "", "{", "", "}", "", ",", ", ", "[", "[ ")
  29. fmt.Fprint(w, replacer.Replace(string(data)))
  30. }

Without using strings.NewReplacer like the code snippet above, i.e. fmt.Fprint(w, string(data)) directly gives me the output below which is not what I want.

  1. [{"id":1011334},{"id":1017100},{"id":1009144},{"id":1010699},{"id":1009146},{"id":1016823},{"id":1009148},{"id":1009149}, ... ]

I somehow feel my way of using strings.NewReplacer is not a clean/proper way. Can anyone suggest a better way of making the output I want?

答案1

得分: 1

创建一个名为int array的数组,其中包含你的ID,并将其编组并写入响应中。

用以下代码替换你的最后三行,并进行测试。

  1. var data []int
  2. for _, result := range characterId.Data.Results {
  3. data = append(data, result.Id)
  4. }
  5. c , err := json.Marshal(data)
  6. if err != nil {
  7. //在这里处理错误
  8. }
  9. fmt.Fprint(w, string(c))
英文:

Create int array with your IDs and marshal it and write it to your response.

Replace your last tree lines with following code and test.

  1. var data []int
  2. for _, result := range characterId.Data.Results {
  3. data = append(data, result.Id)
  4. }
  5. c , err := json.Marshal(data)
  6. if err != nil {
  7. //handle error here
  8. }
  9. fmt.Fprint(w, string(c))

huangapple
  • 本文由 发表于 2021年6月13日 02:08:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/67951680.html
匿名

发表评论

匿名网友

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

确定