将嵌套结构转换为嵌套的JSON动态golang
如何将以下嵌套结构转换
type Details struct {
name string
age int
address *address
dateOfBirth *date
}
type address struct {
street string
city string
state string
country string
}
type date struct {
day int
month string
year int
}
type StudentDetails struct {
details *PersonalDetails
}
为Golang的任何级别的嵌套JSON,类似的东西
{
"Student_1":{
"name":"aaa",
"age":20,
"address":[{
"street":"",
"city":"",
"state":"",
"country":""
},{
"street":"",
"city":"",
"state":"",
"country":""
}],
"date":{
"day":1,
"month":"Jan",
"year":2000
}
},
"Student_2":{
"name":"bbb",
"age":22,
"address":[{
"street":"",
"city":"",
"state":"",
"country":""
},{
"street":"",
"city":"",
"state":"",
"country":""
}],
"date":{
"day":1,
"month":"Feb",
"year":2002
}
}
}
我想根据此结构中的内容动态构建JSON。该结构是通过协议缓冲区构建的。指针指向从中获取细节所需的结构。我曾经反映包裹以访问结构,我能够读取数据,但无法构建数据。任何帮助都将受到赞赏
how do i convert the following nested struct
type Details struct {
name string
age int
address *address
dateOfBirth *date
}
type address struct {
street string
city string
state string
country string
}
type date struct {
day int
month string
year int
}
type StudentDetails struct {
details *PersonalDetails
}
to a nested json of any level in golang, something like this
{
"Student_1":{
"name":"aaa",
"age":20,
"address":[{
"street":"",
"city":"",
"state":"",
"country":""
},{
"street":"",
"city":"",
"state":"",
"country":""
}],
"date":{
"day":1,
"month":"Jan",
"year":2000
}
},
"Student_2":{
"name":"bbb",
"age":22,
"address":[{
"street":"",
"city":"",
"state":"",
"country":""
},{
"street":"",
"city":"",
"state":"",
"country":""
}],
"date":{
"day":1,
"month":"Feb",
"year":2002
}
}
}
i want to build a json dynamically based on what is in this struct. The struct is build from protocol buffer. The pointer points to the struct it needs to fetch the details from. I used to reflect package to access the struct, i'm able to read through the data but not able to build the same. Any help is appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该构造对象,然后使用
json.marshal(obj)
解决方案可能是:
输出为:
You should construct the object and then use
json.Marshal(obj)
The solution may be something like:
The output is: