我在 Go 中創(chuàng)建了一個 API,它在被調用時執(zhí)行查詢,創(chuàng)建一個結構體的實例,然后將該結構體編碼為 JSON,然后再發(fā)送回調用者。我現(xiàn)在希望調用者能夠通過傳入“字段”GET 參數(shù)來選擇他們想要返回的特定字段。這意味著根據字段值,我的結構會改變。有沒有辦法從結構中刪除字段?或者至少將它們動態(tài)隱藏在 JSON 響應中?(注意:有時我有空值,所以 JSON omitEmpty 標簽在這里不起作用)如果這些都不可能,是否有更好的方法來處理這個問題?我正在使用的結構的較小版本如下:type SearchResult struct { Date string `json:"date"` IdCompany int `json:"idCompany"` Company string `json:"company"` IdIndustry interface{} `json:"idIndustry"` Industry string `json:"industry"` IdContinent interface{} `json:"idContinent"` Continent string `json:"continent"` IdCountry interface{} `json:"idCountry"` Country string `json:"country"` IdState interface{} `json:"idState"` State string `json:"state"` IdCity interface{} `json:"idCity"` City string `json:"city"`} //SearchResulttype SearchResults struct { NumberResults int `json:"numberResults"` Results []SearchResult `json:"results"`} //type SearchResults然后我像這樣編碼和輸出響應:err := json.NewEncoder(c.ResponseWriter).Encode(&msg)
從結構中刪除字段或將它們隱藏在 JSON 響應中
函數(shù)式編程
2021-06-18 23:16:08