我有这个json文件,在这个json文件中有我们看到的n个键 A1,B1 ............................................... .......................锌, A1,A2 ............................................... ........................一个, B1 ................................................. .........................亿 等
{
"_id": "5746992a54c1ae24d53ce651",
"A1": [
{
"a1": [
"abc",
"def",
"ghi"
]
},
{
"a2": [
"abc",
"def",
"ghi"
]
},
.
.
,
{
"an": [
"abc",
"def",
"ghi"
]
}
],
"B1": [
{
"b1": [
"abc",
"def",
"ghi"
]
},
{
"b2": [
"abc",
"def",
"ghi"
]
},
{
"bn": [
"abc",
"def",
"ghi"
]
}
],
.
.
.
,
"Bn": [
{
"b1": [
"abc",
"def",
"ghi"
]
},
{
"b2": [
"abc",
"def",
"ghi"
]
},
{
"bn": [
"abc",
"def",
"ghi"
]
}
]
}
如何在golang中调用它们的结构
type Level1 struct {
TAGID bson.ObjectId `json:"_id" bson:"_id"`
LEVELTAG2 []Level2 `json:"level2" bson:"level2"`
}
type LevelTag2 struct{
LEVEL3 []string `json:"level3" bson:"level3"`
}
我在golang中构建这个结构是正确的方式还是其他任何方式 请帮帮我
答案 0 :(得分:3)
当在编译时未知密钥时,您实际上只能使用aps = {
alert = "New message from iphonic";
badge = 1;
eventid = 76;
notifytype = message;
senderuserid = 0;
sound = default;
};
然后使用一些辅助函数来导航该结构。
如果键确实是a1,a2,a3等...你可以创建一个实际的结构,但它不会很漂亮,因为你必须拼出每一个键。
通常,当文档的键是数据的一部分时,您无法真正创建静态结构。
并且通过“部分数据”我的意思是:
map[string]interface{}
VS
{
"billy":23,
"tommy":24
}
第二种形式可表示为: struct {Name string,Age int}
而第一个真的只能是: map [string] int或map [string] interface {}(如果结构很深)
答案 1 :(得分:0)
最好先定义所需的结构(将嵌套结构作为级别)。然后实现UnmarshalJSON([]byte) error接口以转换传入数据所需的结构。
我不想写很长的例子,除非我确定你想要什么=) 我想采用我在Merge a dynamic data structure in Go中使用的类似方法。
你需要那些" A1" ..." ZN",(" a1" ..." an")......( " z1" .." zn")键?或切片就足够了?像:
type S struct {
ID bson.ObjectId
Data [][][]string
}
或者可以转换为内部[]string
[
"abc",
"def",
"ghi"
]
到某个结构,如果只有3个元素?