I've created an API in Go that, upon being called, performs a query, creates an instance of a struct, and then encodes that struct as JSON before sending back to the caller. I'd now like to allow the caller to be able to select the specific fields they would like returned by passing in a "fields" GET parameter.

这意味着根据字段值的不同,我的 struct 会发生变化.有什么方法可以从 struct 中删除字段吗?或者至少将它们动态地隐藏在JSON响应中?(注意:有时我的值为空,因此JSON omitEmpty标记在这里不起作用)如果这两个都不可能,有没有更好的处理方法的建议?

A smaller version of the structs I'm using are below:

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)

推荐答案

The question is asking for fields to be dynamically selected based on the caller-provided list of fields. This isn't possible to be done with the statically-defined json struct tag.

If what you want is to always skip a field to json-encode, then of course use json:"-" to ignore the field. (Note also that this is not required if your field is unexported; those fields are always ignored by the json encoder.) This isn't what the question asks.

引用对json:"-"答案的 comments :

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.您可以通过调用 map 上的delete内置命令轻松删除字段.

That is, if you can't query only for the requested fields in the first place.

Json相关问答推荐

嵌套自定义解组

我如何知道TJSONNumber是double还是double?

在Vega中如何通过滑块改变条形图的宽度

使用JQ在数组中 Select 第一个具有匹配项的项

条件性构建/修改嵌套对象数组

如何使用 JOLT 将带有列表的 JSON 项目取消列出为多个项目?

jolt 通配符如何用于 RHS?

如何在 wso2 中组合 2 个 json 有效负载?

如何在linux中用jq过滤json数组?

Vue 3如何将参数作为json发送到axios get

如何使用 ConfigurationBuilder 解析现有的 json 字符串(不是文件)

如何使用 Swiftui 判断 JSON 是否缺少键值对

JSON 模式验证

如何使用 gson 调用默认反序列化

哪个更好:Json 或 XML (PHP)

Qt使用QJsonDocument、QJsonObject、QJsonArray解析JSON

关于使用 $ref 的 JSON 模式

如何将单引号转义成双引号转成单引号

C++:使用 nlohmann json 从文件中读取 json 对象

Backbone.js 模型与集合