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

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

Removed fieldname id and reformat JSON Output in golang

问题

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

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

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

...

type CharacterId struct {
	Data struct {
		Results []struct {
			Id int `json:"id"`
		} `json:"results"`
	} `json:"data"`
}

func getCharacters(w http.ResponseWriter, _ *http.Request) {
	ts := strconv.FormatInt(time.Now().Unix(), 10)
	hash := getMd5(ts + conf.privateKey + conf.publicKey)

	response, err := http.Get("https://gateway.marvel.com/v1/public/characters?ts=" + ts + "&apikey=" + conf.publicKey + "&hash=" + hash + "&limit=100")
	if err != nil {
		log.Fatal(err)
	}
	defer response.Body.Close()

	responseBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatal(err)
	}

	var characterId CharacterId
	err = json.Unmarshal(responseBytes, &characterId)
	if err != nil {
		log.Fatal(err)
		return
	}

	data, err := json.Marshal(characterId.Data.Results)
	replacer := strings.NewReplacer("\"id\":", "", "{", "", "}", "", ",", ", ", "[", "[ ")
	fmt.Fprint(w, replacer.Replace(string(data)))
}

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

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

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

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

...

type CharacterId struct {
	Data struct {
		Results []struct {
			Id int `json:"id"`
		} `json:"results"`
	} `json:"data"`
}

func getCharacters(w http.ResponseWriter, _ *http.Request) {
	ts := strconv.FormatInt(time.Now().Unix(), 10)
	hash := getMd5(ts + conf.privateKey + conf.publicKey)

	response, err := http.Get("https://gateway.marvel.com/v1/public/characters?ts=" + ts + "&apikey=" + conf.publicKey + "&hash=" + hash + "&limit=100")
	if err != nil {
		log.Fatal(err)
	}
	defer response.Body.Close()

	responseBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatal(err)
	}

	var characterId CharacterId
	err = json.Unmarshal(responseBytes, &characterId)
	if err != nil {
		log.Fatal(err)
		return
	}

	data, err := json.Marshal(characterId.Data.Results)
	replacer := strings.NewReplacer("\"id\":", "", "{", "", "}", "", ",", ", ", "[", "[ ")
	fmt.Fprint(w, replacer.Replace(string(data)))
}

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.

[{"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,并将其编组并写入响应中。

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

    var data []int
	for _, result := range characterId.Data.Results {
		data = append(data, result.Id)
	}
	c , err := json.Marshal(data)
	if err != nil {
		//在这里处理错误
	}
	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.

    var data []int
for _, result := range characterId.Data.Results {
data = append(data, result.Id)
}
c , err := json.Marshal(data)
if err != nil {
//handle error here
}
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:

确定