英文:
How to Unmarshal jSON with dynamic key which can't be captured as a `json` in struct: GOlang
问题
我有这个定义的结构体:
type X struct {
A string `json:"a_known_string"`
B string `json:"b_known_string"`
}
这是一个示例的JSON:
jsnStr := [从文件中读取并打印出来确认]
它是这样的:
{
"any string" : {
"a_known_string" : "some value",
"b_known_string" : "another value"
}
}
如果只有结构体,我可以这样做:
var x X
err := json.Unmarshal(jsnStr, &x)
但我需要捕获那个 'any string'。
请问我该如何做?
英文:
I have this struct defined:
type X struct {
A string `json:"a_known_string"`
B string `json:"b_known_string"`
}
This sample JSON:
jsnStr := [read in from a file and printed out to confirm]
It is:
{
"any string" : {
"a_known_string" : "some value",
"b_known_string" : "another value"
}
}
If it was just the struct, I could:
var x X
err := json.Unmarshal(jsnStr, &x)
But I need to capture that 'any string'.
How do I do that please?
答案1
得分: 4
使用地图:
var m map[string]X
err := json.Unmarshal([]byte(jsnStr), &m)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论