如何在Go中从JSON中删除字段?

huangapple go评论69阅读模式
英文:

How to remove fields from json in go?

问题

我在代码中有这个结构体。

type AppVersion struct {
    Id            int64     `json:"id"`
    App           App       `json:"app,omitempty" out:"false"`
    AppId         int64     `sql:"not null" json:"app_id"`
    Version       string    `sql:"not null" json:"version"`
    Sessions      []Session `json:"-"`
    SessionsCount int       `sql:"-"`
    CreatedAt     time.Time `json:"created_at"`
    UpdatedAt     time.Time `json:"updated_at"`
    DeletedAt     time.Time `json:"deleted_at"`
}

我正在构建一个 Web 服务,我不需要在 JSON 中发送 App 字段。
我尝试了一些方法来从 JSON 中删除该字段,但是我没有成功。

我该如何实现这个目标?
有没有办法将结构体设置为空?

我正在使用 GORM 作为数据库访问层,所以我不确定是否可以使用 App *App,你知道这样是否可行吗?

英文:

I've this struct in my code.

type AppVersion struct {
	Id            int64     `json:"id"`
	App           App       `json:"app,omitempty" out:"false"`
	AppId         int64     `sql:"not null" json:"app_id"`
	Version       string    `sql:"not null" json:"version"`
	Sessions      []Session `json:"-"`
	SessionsCount int       `sql:"-"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
	DeletedAt     time.Time `json:"deleted_at"`
}

I'm building a webservice and I don't need to send the App field in the JSON.
I've tried a few things to remove the field from the JSON but I haven't been able to do it.

How can I achieve this?
Is there any way to set struct as empty?

I'm using GORM as database access layer, so I'm not sure if I can do App *App, do you know if it will work?

答案1

得分: 2

类型 AppVersion 结构体 {
Id int64 json:"id"
App App json:"-"
AppId int64 sql:"not null" json:"app_id"
Version string sql:"not null" json:"version"
Sessions []Session json:"-"
SessionsCount int sql:"-"
CreatedAt time.Time json:"created_at"
UpdatedAt time.Time json:"updated_at"
DeletedAt time.Time json:"deleted_at"
}

更多信息 - json-go

英文:
type AppVersion struct {
    Id            int64     `json:"id"`
    App           App       `json:"-"`
    AppId         int64     `sql:"not null" json:"app_id"`
    Version       string    `sql:"not null" json:"version"`
    Sessions      []Session `json:"-"`
    SessionsCount int       `sql:"-"`
    CreatedAt     time.Time `json:"created_at"`
    UpdatedAt     time.Time `json:"updated_at"`
    DeletedAt     time.Time `json:"deleted_at"`
}

More info - json-go

答案2

得分: 1

你应该能够将你的数据结构封装到一个自定义类型中,该类型隐藏了App字段:

type ExportAppVersion struct {
   AppVersion
   App `json:"-"`
}

这样就可以隐藏App字段,不会被暴露出来。

英文:

You should be able to wrap your data structure into a custom type which hides the app field:

type ExportAppVersion struct {
   AppVersion
   App `json:"-"`
}

This should hide the App field from being exposed.

huangapple
  • 本文由 发表于 2014年10月24日 21:20:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/26548732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定