mysql - Omitempty 字段不起作用,如何从响应正文中删除空结构?
问题描述
type PolicySpec struct {
Description string `json:"description" yaml:"description"`
EndpointSelector Selector `json:"endpointSelector,omitempty" yaml:"ingress,omitempty"`
Severity int `json:"severity,omitempty" yaml:"severity,omitempty"`
Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"`
Message string `json:"message,omitempty" yaml:"message,omitempty"`
Process KubeArmorSys `json:"process,omitempty" yaml:"process,omitempty"`
File KubeArmorSys `json:"file,omitempty" yaml:"network,omitempty"`
Action string `json:"action,omitempty" yaml:"action,omitempty"`
}
我即使在字段中添加了 omitempty 却在 yaml 和 json 中获得了空结构,如何从 api 响应正文中删除那些空结构?
解决方案
正如 Go 中 yaml 库的文档所描述的,空结构体应该用omitempty
标签省略。链接 - pkg.go.dev/gopkg.in/yaml.v3
省略
Only include the field if it's not set to the zero value for the type or to empty slices or maps. Zero valued structs will be omitted if all their public fields are zero, unless they implement an IsZero method (see the IsZeroer interface type), in which case the field will be excluded if IsZero returns true.
这是示例证明代码。
package main
import (
"fmt"
"gopkg.in/yaml.v3"
"log"
)
type A struct {
A int `yaml:"a"`
}
type B struct {
B int `yaml:"b"`
A A `yaml:"a,omitempty"`
}
func main() {
b := B{
B:5,
}
encoded, err := yaml.Marshal(b)
if err != nil {
log.Fatalln(err)
}
fmt.Println(`encoded - `,string(encoded)) //encoded - b: 5
}
你可以在这里运行代码
推荐阅读
- java - 如何关闭 Openshift 容器中的非 Java 日志?
- algorithm - 为什么在分析递归算法的运行时间时会出现递归关系?
- android - 在android中是否可以有2个菜单项(AppBar),一个左对齐,一个右对齐?
- node.js - 为什么我的 get api 不起作用但 post api 可以发布到 mongodb
- reactjs - 无法读取 null 的属性“pageX”
- python - 如何修复错误:int() 以 10 为底的无效文字:'Luck'?
- php - 在 OSX 上安装 PHP 7.4.2
- r - gsub 和 str_extract
- python - 计算列中的天数 groupby
- mysql - MySql使用列号生成密码