我在 Go 中创建了一个 API,它在被调用时执行查询,创建结构的实例,然后将该结构编码为 JSON,然后再发送回调用者。我现在想让调用者能够通过传入“fields”GET 参数来选择他们想要返回的特定字段。
这意味着根据字段值,我的结构会发生变化。有没有办法从结构中删除字段?或者至少将它们动态地隐藏在 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"`
} //SearchResult
type SearchResults struct {
NumberResults int `json:"numberResults"`
Results []SearchResult `json:"results"`
} //type SearchResults
然后我像这样编码并输出响应:
err := json.NewEncoder(c.ResponseWriter).Encode(&msg)
原文由 user387049 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题是要求根据调用者提供的字段列表 动态 选择字段。这不可能用静态定义的 json 结构标签来完成。
如果您想要的是 始终 跳过某个字段进行 json 编码,那么当然可以使用
json:"-"
来忽略该字段。 (另请注意,如果您的字段未导出,则 不需 要这样做;json 编码器始终会忽略这些字段。)这不是问题所在。引用对
json:"-"
的评论回答:在这种情况下,我会使用
map[string]interface{}
而不是结构。您可以通过调用地图上内置的delete
轻松删除字段,以便删除字段。也就是说,如果您一开始不能只查询请求的字段。