英文:
How to represent Golang struct with variable field names
问题
如果这个问题已经在其他地方得到解答,请告诉我,但我找不到任何相关信息。
基本上,假设我们有以下的 JSON 数据。string-id-001
可以是任意字符串。我们想要将其解析为一个结构体,并能够访问唯一的 id。
{"list":{"string-id-001":{"id":"blah","name":"cool"},"string-id-002":{"id":"yas","name":"rad"}}}
据我所知,使用 Golang 需要类似下面的代码,但如果 keyhere
的值不断变化的话,这种方法是行不通的。例如,如果它是一个 ID。
type Foo struct {
List struct {
StringID001 struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"string-id-001"`
StringID002 struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"string-id-002"`
} `json:"list"`
}
我在另一个项目中遇到了类似的问题(我是通过接口而不是结构体来解决的),我想知道是否有更好的解决方案。我是否忽略了一些明显的东西?
英文:
If this has been answered somewhere else let me know but I couldn't find anything.
Basically, let's say we have the following JSON. string-id-001
can be an arbitrary string. We want to unmarshal it into a struct, and be able to access the unique id's.
{"list":{"string-id-001":{"id":"blah","name":"cool"},"string-id-002":{"id":"yas","name":"rad"}}}
Golang as far as I can tell would require something like below which doesn't work if the keyhere
value is constantly changing. Eg if it's an ID
type Foo struct {
List struct {
StringID001 struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"string-id-001"`
StringID002 struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"string-id-002"`
} `json:"list"`
}
I've seen a similar issue in another project (which I solved with interfaces rather than structs), and I'm wondering if there's a nicer solution. Am I missing something obvious?
答案1
得分: 2
类型 payLoad struct {
ID string `json:"id"`
Name string `json:"name"`
}
类型 Foo struct {
List map[string]payLoad `json:"list"`
}
英文:
type payLoad struct {
ID string `json:"id"`
Name string `json:"name"`
}
type Foo struct {
List map[string]payLoad `json:"list"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论