首页
学习
活动
专区
工具
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标记在这里不起作用)如果这两个都不可能,有没有更好的处理方法的建议?

下面是我正在使用的结构的一个较小版本:

代码语言:javascript
复制
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

然后对响应进行编码并输出,如下所示:

代码语言:javascript
复制
err := json.NewEncoder(c.ResponseWriter).Encode(&msg)
EN

回答 8

Stack Overflow用户

发布于 2014-03-28 15:46:32

使用json:"-"

代码语言:javascript
复制
// 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

票数 187
EN

Stack Overflow用户

发布于 2017-01-27 02:53:09

我刚刚发布了sheriff,它根据结构字段上注释的标记将结构转换为映射。然后,您可以编组(JSON或其他)生成的映射。它可能不允许您只序列化调用者请求的字段集,但我想使用一组组将允许您涵盖大多数情况。使用组而不是直接使用字段也很可能会增加缓存能力。

示例:

代码语言:javascript
复制
package main

import (
    "encoding/json"
    "fmt"
    "log"

    "github.com/hashicorp/go-version"
    "github.com/liip/sheriff"
)

type User struct {
    Username string   `json:"username" groups:"api"`
    Email    string   `json:"email" groups:"personal"`
    Name     string   `json:"name" groups:"api"`
    Roles    []string `json:"roles" groups:"api" since:"2"`
}

func main() {
    user := User{
        Username: "alice",
        Email:    "alice@example.org",
        Name:     "Alice",
        Roles:    []string{"user", "admin"},
    }

    v2, err := version.NewVersion("2.0.0")
    if err != nil {
        log.Panic(err)
    }

    o := &sheriff.Options{
        Groups:     []string{"api"},
        ApiVersion: v2,
    }

    data, err := sheriff.Marshal(o, user)
    if err != nil {
        log.Panic(err)
    }

    output, err := json.MarshalIndent(data, "", "  ")
    if err != nil {
        log.Panic(err)
    }
    fmt.Printf("%s", output)
}
票数 9
EN

Stack Overflow用户

发布于 2013-06-26 15:46:16

你可以使用标签属性"omitifempty“,或者将可选字段设为指针,而不初始化那些你想跳过的字段。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17306358

复制
相关文章

相似问题

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