Question:
Is it possible to unmarshal JSON with fieldnames that are unknown in advance, while maintaining the given structure?
Problem:
Consider a JSON response where unknown fieldnames wrap a common structure. This structure must be mapped to a struct, but the fieldnames vary.
{ "unknown_field": { "known_field_1": [[1,2,3,4,5],[10,20,30,40,50],[100,200,300,400,500]], "known_field_2": [[11,21,31,41,51]], "known_field_3": [[12,22,32,42,52],[14,44,34,44,54]] } }
Answer:
Yes, it is possible to unmarshal such JSON using a map as the root struct element, where keys are the unknown fieldnames and values are instances of the known struct.
type mData struct { KnownField1 [][5]int `json:"known_field_1"` KnownField2 [][5]int `json:"known_field_2"` KnownField3 [][5]int `json:"known_field_3"` }
var data map[string]mData if err := json.Unmarshal(body, &data); err != nil { panic(err) }
Output:
map[unknown_field:{[[1 2 3 4 5] [10 20 30 40 50] [100 200 300 400 500]] [[11 21 31 41 51]] [[12 22 32 42 52] [14 44 34 44 54]]}] unknown_field {[[1 2 3 4 5] [10 20 30 40 50] [100 200 300 400 500]] [[11 21 31 41 51]] [[12 22 32 42 52] [14 44 34 44 54]]}
The above is the detailed content of How to Unmarshal JSON with Unexpected Field Names into a Go Struct?. For more information, please follow other related articles on the PHP Chinese website!