首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从结构中删除字段或将其隐藏在JSON响应中

从结构中删除字段或将其隐藏在JSON响应中
EN

Stack Overflow用户
提问于 2013-06-26 03:56:20
回答 8查看 191.1K关注 0票数 229

我在Go中创建了一个API,它在被调用时执行查询,创建一个结构的实例,然后在发送回调用者之前将该结构编码为JSON。现在,我想让调用者能够通过传递一个“field”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)
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17306358

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档