Home >Backend Development >Golang >How to Unmarshal JSON with Unknown Field Names into a Go Struct?
This scenario arises when the JSON response contains fields with unknown or dynamic names. To address this, we can utilize a combination of a map and a struct to capture the data.
Modified Code:
package main import "fmt" import "encoding/json" var body = []byte(`{ "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]] } }`) 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 func main() { if err := json.Unmarshal(body, &data); err != nil { panic(err) } fmt.Println(data) for k, v := range data { fmt.Println(k, v) } }
Explanation:
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 Unknown Field Names into a Go Struct?. For more information, please follow other related articles on the PHP Chinese website!