Golang中的嵌套json如何解组为简单的json对象?
来源:stackoverflow
2024-02-08 09:36:24
0浏览
收藏
最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《Golang中的嵌套json如何解组为简单的json对象?》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~
问题内容
嗨,我需要一些帮助,我来自nodejs,正在寻找一种方法来解组嵌套的json,使其成为简单的json对。 这是我的嵌套 json 的示例。
{ "id": 1000004, "reference": "t0000", "amount": 700000, "paid_at": "2022-07-24t00:49:13.000z", "created_at": "2022-07-24t00:49:08.000z", "metadata": { "custom_fields": [ { "display_name": "meternumber", "value": "123456789" }, { "display_name": "accountnumber", "value": "123456" } ] } }
我想实现这个:
{ "id": 1000004, "reference": "t0000", "amount": 700000, "paid_at": "2022-07-24t00:49:13.000z", "created_at": "2022-07-24t00:49:08.000z", "meter_number": "123456789", "account_number": "123456", }
它曾经是一个深根嵌套的有效负载,我已经使用结构类型来隔离相关的对和数组,但它仍然不是我需要传递到数据库的格式。 指针和更正将不胜感激。
如何将嵌套的 json 解组为简单的 json 对 golang?
这是原始数据
data = []byte(`{ "status": true, "message": "transactions retrieved", "data": [ { "id": 10000000, "domain": "test", "status": "success", "reference": "t0000000000", "amount": 700000, "message": null, "gateway_response": "successful", "paid_at": "2022-07-24t00:49:13.000z", "created_at": "2022-07-24t00:49:08.000z", "channel": "card", "currency": "ngn", "ip_address": "102.89.32.12", "metadata": { "custom_fields": [ { "display_name": "meternumber", "variable_name": "meternumber", "value": "123456789" }, { "display_name": "accountnumber", "variable_name": "accountnumber", "value": "123456" } ], "referrer": "https://example.com/" }, "log": { "start_time": 1658623749, "time_spent": 4, "attempts": 1, "errors": 0, "success": true, "mobile": false, "input": [], "history": [ { "type": "action", "message": "attempted to pay with card", "time": 2 }, { "type": "success", "message": "successfully paid with card", "time": 4 } ] }, "fees": 20500, "fees_split": null, "customer": { "id": 87000000, "first_name": "foo", "last_name": "foo", "email": "[email protected]", "phone": "08090000000", "metadata": null, "customer_code": "cus_foo", "risk_action": "default" }, "authorization": { "authorization_code": "auth_foo", "bin": "40123456789", "last4": "40000", "exp_month": "12", "exp_year": "2030", "channel": "card", "card_type": "visa ", "bank": "test bank", "country_code": "ng", "brand": "visa", "reusable": true, "signature": "sig_foo", "account_name": null }, "plan": {}, "split": {}, "subaccount": {}, "order_id": 800000, "paidat": "2022-07-24t00:49:13.000z", "createdat": "2022-07-24t00:49:08.000z", "requested_amount": 700000, "source": { "source": "checkout", "type": "web", "identifier": null, "entry_point": "request_inline" }, "pos_transaction_data": null }, { "id": 1000000, "domain": "test", "status": "success", "reference": "t13456789", "amount": 500000, "message": null, "gateway_response": "successful", "paid_at": "2022-07-24t00:28:34.000z", "created_at": "2022-07-24t00:28:08.000z", "channel": "card", "currency": "ngn", "ip_address": "192.168.1.1", "metadata": { "custom_fields": [ { "display_name": "meternumber", "variable_name": "meternumber", "value": "123456789" }, { "display_name": "accountnumber", "variable_name": "accountnumber", "value": "123456" } ], "referrer": "https://example.com" }, "log": { "start_time": 1658622488, "time_spent": 26, "attempts": 1, "errors": 0, "success": true, "mobile": false, "input": [], "history": [ { "type": "action", "message": "set payment method to: bank", "time": 15 }, { "type": "action", "message": "set payment method to: ussd", "time": 16 }, { "type": "action", "message": "set payment method to: bank", "time": 19 }, { "type": "action", "message": "set payment method to: card", "time": 22 }, { "type": "action", "message": "attempted to pay with card", "time": 25 }, { "type": "success", "message": "successfully paid with card", "time": 26 } ] }, "fees": 17500, "fees_split": null, "customer": { "id": 870000000, "first_name": "foo", "last_name": "foo", "email": "[email protected]", "phone": "0809000000", "metadata": null, "customer_code": "cus_xxxx", "risk_action": "default" }, "authorization": { "authorization_code": "auth_xxxx", "bin": "400000", "last4": "40000", "exp_month": "12", "exp_year": "2030", "channel": "card", "card_type": "visa ", "bank": "test bank", "country_code": "ng", "brand": "visa", "reusable": true, "signature": "xxxxxx", "account_name": null }, "plan": {}, "split": {}, "subaccount": {}, "order_id": 827512, "paidat": "2022-07-24t00:28:34.000z", "createdat": "2022-07-24t00:28:08.000z", "requested_amount": 500000, "source": { "source": "checkout", "type": "web", "identifier": null, "entry_point": "request_inline" }, "pos_transaction_data": null } ], "meta": { "total": 2, "total_volume": 12000, "skipped": 0, "perpage": 50, "page": 1, "pagecount": 1 } }`)
这就是我所做的:
type Uservariabledata struct { //json.RawMessage `json:"custom_field"` Display_name string `json:"display_name"` Value string `json:"value"` } // struct type UserDataDetail struct { Custom_fields []Uservariabledata } // struct type UserData struct { Id int `json:"id"` Reference string `json:"reference"` Amount uint `json:"amount"` Paid_at string `json:"paid_at"` Created_at string `json:"created_at"` Metadata UserDataDetail } // Payload struct type Payload struct { Status bool `json:"status"` Message string `json:"message"` Data []UserData Meta json.RawMessage `json:"meta"` } func (p *Payload) UnmarshalJSON(data []byte) error { type payload struct { Status bool `json:"status"` Message string `json:"message"` Data []UserData Meta json.RawMessage `json:"meta"` } payld := &payload{} err := json.Unmarshal(data, payld) if err != nil { return err } p.Status = payld.Status p.Message = payld.Message p.Data=payld.Data p.Meta=payld.Meta return nil } // GetUserAmountPaid endpoint, this was done in my controller.go func GetUserAmountPaid(c echo.Context) (err error) { respData := Data payld := Payload{} err = json.Unmarshal(respData, &payld) if err != nil { panic(err) } return c.JSON(http.StatusOK, payld.Data) }
正确答案
您主要已经确定您希望为“真实数据”和“传输数据”拥有单独的结构。
type realdata struct { id int `json:"id"` ... meternumber string `json:"meter_number"` accountnumber string `json:"account_number"` }
诀窍在于您的“传输数据”不太正确,它需要与正在解析的 json 的格式相匹配。
type transferdata struct { id int // ... metadata struct { custom_fields []struct{ display_name string variable_name string value string } } }
然后只需解组为“传输数据”类型的对象并将其复制到“真实数据”中即可。
func (realData *RealData) UnmarshalJSON(data []byte) error { var transferData TransferData err := json.Unmarshal(data, &transferData) if err != nil { return err } realData.Id = transferData.Id // ... // Now we must cherry-pick the known custom metadata fields we // care about into the desired fields of our real data. for _, cf := range transferData.Metadata.Custom_fields { switch cf.Display_name { case "MeterNumber": realData.MeterNumber = cf.Value case "AccountNumber": realData.AccountNumber = cf.Value } } return nil }
到这里,我们也就讲完了《Golang中的嵌套json如何解组为简单的json对象?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除

- 上一篇
- 如何解决Win10账户名称更改选项消失的问题

- 下一篇
- 实现自动重定向的方法详解
查看更多
最新文章
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
查看更多
AI推荐
-
- 美图AI抠图
- 美图AI抠图,依托CVPR 2024竞赛亚军技术,提供顶尖的图像处理解决方案。适用于证件照、商品、毛发等多场景,支持批量处理,3秒出图,零PS基础也能轻松操作,满足个人与商业需求。
- 11次使用
-
- PetGPT
- SEO摘要PetGPT 是一款基于 Python 和 PyQt 开发的智能桌面宠物程序,集成了 OpenAI 的 GPT 模型,提供上下文感知对话和主动聊天功能。用户可高度自定义宠物的外观和行为,支持插件热更新和二次开发。适用于需要陪伴和效率辅助的办公族、学生及 AI 技术爱好者。
- 11次使用
-
- 可图AI图片生成
- 探索快手旗下可灵AI2.0发布的可图AI2.0图像生成大模型,体验从文本生成图像、图像编辑到风格转绘的全链路创作。了解其技术突破、功能创新及在广告、影视、非遗等领域的应用,领先于Midjourney、DALL-E等竞品。
- 41次使用
-
- MeowTalk喵说
- MeowTalk喵说是一款由Akvelon公司开发的AI应用,通过分析猫咪的叫声,帮助主人理解猫咪的需求和情感。支持iOS和Android平台,提供个性化翻译、情感互动、趣味对话等功能,增进人猫之间的情感联系。
- 38次使用
-
- Traini
- SEO摘要Traini是一家专注于宠物健康教育的创新科技公司,利用先进的人工智能技术,提供宠物行为解读、个性化训练计划、在线课程、医疗辅助和个性化服务推荐等多功能服务。通过PEBI系统,Traini能够精准识别宠物狗的12种情绪状态,推动宠物与人类的智能互动,提升宠物生活质量。
- 36次使用
查看更多
相关文章
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览