Golang 中使用 JSON 的一些小技巧
临时忽略struct字段
type User struct {
Email string `json:"email"`
Password string `json:"password"`
// many more fields…
}
临时忽略掉Password字段
json.Marshal(struct {
*User
Password bool `json:"password,omitempty"`
}{
User: user,
})
临时添加额外的字段
type User struct {
Email string `json:"email"`
Password string `json:"password"`
// many more fields…
}
临时忽略掉Password字段,并且添加token字段
json.Marshal(struct {
*User
Token string `json:"token"`
Password bool `json:"password,omitempty"`
}{
User: user,
Token: token,
})
临时粘合两个struct
type BlogPost struct {
URL string `json:"url"`
Title string `json:"title"`
}
type Analytics struct {
Visitors int `json:"visitors"`
PageViews int `json:"page_views"`
}
json.Marshal(struct{
*BlogPost
*Analytics
}{post, analytics})
一个json切分成两个struct
json.Unmarshal([]byte(`{
"url": "attila@attilaolah.eu",
"title": "Attila's Blog",
"visitors": 6,
"page_views": 14
}`), &struct {
*BlogPost
*Analytics
}{&post, &analytics})
临时改名struct的字段
type CacheItem struct {
Key string `json:"key"`
MaxAge int `json:"cacheAge"`
Value Value `json:"cacheValue"`
}
json.Marshal(struct{
*CacheItem
// Omit bad keys
OmitMaxAge omit `json:"cacheAge,omitempty"`
OmitValue omit `json:"cacheValue,omitempty"`
// Add nice keys
MaxAge int `json:"max_age"`
Value *Value `json:"value"`
}{
CacheItem: item,
// Set the int by value:
MaxAge: item.MaxAge,
// Set the nested struct by reference, avoid making a copy:
Value: &item.Value,
})
用字符串传递数字
type TestObject struct {
Field1 int `json:",string"`
}
这个对应的json是 {"Field1": "100"}
容忍字符串和数字互转
如果你使用的是jsoniter,可以启动模糊模式来支持 PHP 传递过来的 JSON
-
import "github.com/json-iterator/go/extra"
原文链接:https://blog.csdn.net/kingmax54212008/article/details/77869972
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
2023-10-24 Go的文件操作:读写文件与IO接口
2023-10-24 iptables 初始化(docker)
2023-10-24 Linux利用iptables实现真-全局代理
2022-10-24 go柳叶刀工具集合
2022-10-24 Go 语言 errgroup 库的使用方式和实现原理
2021-10-24 Go 语言陷阱 - 数组和切片
2021-10-24 go判断类型是否实现接口所有方法