问题
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:
Use a map:
var m map[string]X
err := json.Unmarshal([]byte(jsnStr), &m)
playground example
来源:https://stackoverflow.com/questions/35558039/how-to-unmarshal-json-with-dynamic-key-which-cant-be-captured-as-a-json-in-st