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

新手上路,请多包涵

我在 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 许可协议

阅读 1.3k
2 个回答

问题是要求根据调用者提供的字段列表 动态 选择字段。这不可能用静态定义的 json 结构标签来完成。

如果您想要的是 始终 跳过某个字段进行 json 编码,那么当然可以使用 json:"-" 来忽略该字段。 (另请注意,如果您的字段未导出,则 不需 要这样做;json 编码器始终会忽略这些字段。)这不是问题所在。

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

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

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

也就是说,如果您一开始不能只查询请求的字段。

原文由 mna 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 `json:“-”`

 // Field is ignored by this package.
Field int `json:"-"`

// Field appears in JSON as key "myName".
Field int `json:"myName"`

// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `json:"myName,omitempty"`

// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`

文档:http: //golang.org/pkg/encoding/json/#Marshal

原文由 GivenJazz 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题