我在 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)
最佳答案
问题是要求根据调用方提供的字段列表动态选择字段。使用静态定义的 json 结构标记无法做到这一点。
如果您想要总是跳过一个字段以进行 json-encode,那么当然使用 json:"-"
来忽略该字段。 (另请注意,如果您的字段未导出,则不需要;这些字段总是被 json 编码器忽略。)这不是问题要问的。
引用json:"-"
上的评论回答:
This [the
json:"-"
answer] is the answer most people ending up here from searching would want, but it's not the answer to the question.
在这种情况下,我会使用 map[string]interface{}
而不是结构。您可以通过调用 map 上内置的 delete
来轻松删除字段以删除字段。
也就是说,如果您一开始就不能只查询请求的字段。
https://stackoverflow.com/questions/17306358/