加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang从struct中删除字段或将其隐藏在JSON响应中

发布时间:2020-12-16 18:08:39 所属栏目:大数据 来源:网络整理
导读:我在Go中创建了一个API,在被调用时,执行查询,创建一个结构的实例,然后在将该结构编码为JSON之后再发送回调用者。现在我想允许调用者通过传入“fields”GET参数来选择他们想要返回的特定字段。 这意味着根据字段值,我的结构将改变。有没有办法从结构中删
我在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)
编辑:我注意到一些downvote,并再次看看这个问答。大多数人似乎错过了OP要求动态选择字段基于调用者提供的字段列表。你不能用静态定义的json结构标记来做到这一点。

如果你想要的是总是跳过一个字段json-encode,然后当然使用json:“ – ”忽略该字段(还要注意,如果你的字段未导出,这不是必需的 – 这些字段总是被json忽略编码器)。但这不是OP的问题。

引用对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 {}而不是struct。您可以通过在地图上调用删除内置字段来轻松删除字段,以删除字段。

也就是说,如果您不能首先查询请求的字段。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读