在 golang 中动态从 JSON 中删除密钥
来源:stackoverflow
时间:2024-04-28 18:09:34 260浏览 收藏
一分耕耘,一分收获!既然都打开这篇《在 golang 中动态从 JSON 中删除密钥》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!
我有一个不同的 json 架构 (json.rawmessage),可以具有任意格式。我不知道编译时的格式。
在 golang 中,我想检查根 json 对象中是否存在密钥,如果存在,则完全删除该密钥并反序列化。
例如,假设我需要删除“foo”(如果存在)
{ "foo": [1,2,3], "bar123":"baz"} -> {"bar123":"baz" }
{ "foo": "test", "bar123":"baz"} -> { "bar123":"baz" }
{ "foo": {"bar":"bar2"}, "bar123":"baz"} -> { "bar123":"baz" }
{ "bar123":"baz"} -> { "bar123":"baz" }
{ "foo": {"bar":"bar2"}} -> {}
鉴于我需要提前知道 json 的结构来进行序列化和反序列化,我该如何使用 go 来做到这一点?
解决方案
如果您对 json 一无所知,则可以将其解组为 interface{} 类型的值。 encoding/json 软件包将为 json 对象选择 map[string]interface{},为 json 数组选择 []interface{}。
您可以使用类型断言来检查结果是否是映射,并且可以从中删除 "foo" 键,然后再次封送它:
例如:
inputs := []string{`{ "foo": [1,2,3], "bar":"baz"}`,
`{ "foo": "test", "bar123":"baz"}`,
`{ "foo": {"bar":"bar2"}, "bar123":"baz"}`,
`{ "bar123":"baz"}`,
`{ "foo": {"bar":"bar2"}}`,
}
for _, input := range inputs {
var i interface{}
if err := json.unmarshal([]byte(input), &i); err != nil {
panic(err)
}
if m, ok := i.(map[string]interface{}); ok {
delete(m, "foo") // no problem if "foo" isn't in the map
}
output, err := json.marshal(i)
if err != nil {
panic(err)
}
fmt.println(string(output))
}
输出(在 Go Playground 上尝试):
{"bar":"baz"}
{"bar123":"baz"}
{"bar123":"baz"}
{"bar123":"baz"}
{}
如果您确定输入是 json 对象,则可以直接解组为 map[string]interface{} 类型的映射(或者更好:解组为 map[string]json.rawmessage),因此代码会更简单:
var m map[string]json.rawmessage
if err := json.unmarshal([]byte(input), &m); err != nil {
panic(err)
}
delete(m, "foo")
拨打 Go Playground 试试这个。
另一个优化是检查键 "foo" 是否确实在映射中,如果是,则仅将其删除并编组修改后的映射。否则输入将是输出(无需更改):
var m map[string]json.rawmessage
if err := json.unmarshal([]byte(input), &m); err != nil {
panic(err)
}
output := input
if _, exists := m["foo"]; exists {
delete(m, "foo")
outputdata, err := json.marshal(m)
if err != nil {
panic(err)
}
output = string(outputdata)
}
fmt.println(output)
在 Go Playground 上尝试这个。
我个人喜欢使用 gabs 模块,它允许以更人性化的方式处理此类情况。
要安装模块,请使用:
go get github.com/jeffail/gabs/v2
因此,如果存在,则动态删除键
// jsonParsed var contains a set of functions to play arround
jsonParsed, _ := gabs.ParseJSON([]byte(`{
"outter":{
"inner":{
"value1":10,
"value2":22
},
"alsoInner":{
"value1":20
}
}
}`))
// for this case, it's useful Exists or ExistsP functions
exists := jsonParsed.Exists("outter", "inner", "value1")
// exists == true
exists = jsonParsed.ExistsP("outter.inner.value3")
// exists == false
// for delete a key ... you can use Delete or DeleteP functions.
// this validate for you whether or not the key exists
jsonParsed.DeleteP("outter", "inner")
// and check it with a nice pretty-print
fmt.Println(jsonParsed.StringIndent("", " "))
// "outter: {
// "alsoInner: {
// "value: 20
// }
// }
理论要掌握,实操不能落!以上关于《在 golang 中动态从 JSON 中删除密钥》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
Golang · Go问答 | 15小时前 | channel · goroutine · pprof · Go问答 · 线上排查 · pprof Go问答 Go channel阻塞 goroutine堆积 channel发送205 收藏
-
Golang · Go问答 | 16小时前 | 连接池 · database/sql · Go问答 · 线上排查 · DBStats · MaxOpenConns Go数据库连接池 DBStats Go问答 sql.DB WaitCount355 收藏
-
467 收藏
-
Golang · Go问答 | 17小时前 | EventSource · sse · Go问答 · http.Flusher · 实时推送 · EventSource FLUSH text/event-stream Go问答 http.Flusher Go SSE333 收藏
-
Golang · Go问答 | 17小时前 | 并发安全 · RWMutex · sync.Map · Go问答 · map并发 · RWMutex sync.Map Go问答 Go map并发读写 concurrent map writes102 收藏
-
166 收藏
-
Golang · Go问答 | 5天前 | 并发 · channel · select · 性能排查 · Go问答 · select Go channel context default CPU飙高 忙等循环 ticker438 收藏
-
Golang · Go问答 | 5天前 | pprof · trace · 性能排查 · Go问答 · 服务安全 · Go pprof 生产环境 trace 安全入口 net/http/pprof 性能排障349 收藏
-
Golang · Go问答 | 5天前 | channel · 并发编程 · Go问答 · 背压 · 容量规划 · Goroutine channel 缓冲区 背压 Go问答 buffered channel 并发容量377 收藏
-
Golang · Go问答 | 5天前 | interface · 单元测试 · 架构设计 · repository · Go问答 · 单元测试 架构设计 interface 接口设计 Go问答 调用方定义 Repository212 收藏
-
Golang · Go问答 | 5天前 | JSON · time.Time · 接口设计 · Go问答 · encoding/json · encoding/json API响应 JSON序列化 time.Time omitempty Go问答 omitzero315 收藏
-
Golang · Go问答 | 5天前 | HTTP · Cookie · 浏览器 · cors · Go问答 · SameSite · cookie cors Secure SameSite Go问答 Set-Cookie 跨站请求 credentials246 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习