小编典典

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

javascript

我在 Go 中创建了一个 API,它在被调用时执行查询,创建结构的实例,然后将该结构编码为 JSON,然后发送回调用者。我现在希望调用者能够通过传入“字段”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)

阅读 248

收藏
2021-11-03

共1个答案

小编典典

问题是要求根据调用者提供的字段列表动态选择字段。使用静态定义的 json 结构标记无法做到这一点。

如果你想要总是跳过一个字段到 json-encode,那么当然使用json:"-"忽略该字段。(另请注意,如果您的字段未导出,则这不是必需的;这些字段总是被 json 编码器忽略。)这不是问题所要问的。

引用对json:"-"答案的评论:

这个 [json:"-"答案] 是大多数人从搜索结果到这里想要的答案,但这不是问题的答案。

map[string]interface{}在这种情况下,我会使用 a而不是 struct 。您可以通过调用delete地图上的内置函数来轻松删除字段以删除字段。

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

2021-11-03