Home >Backend Development >Golang >How to unmarshal json with unknown fields and keys
From the front end I got this json example:
{ "properties":{"unknown key": "unknown value","unknown key2": "unknown value 2"} }
I started parsing it with map[string]interface{} but it doesn't work. I also don’t know how much I can gain in this field. Can be 10 or 1.
Code:
type test struct { p map[string]string `json:"properties"` } func main() { var t test body := ` { "properties":{"unknown key": "unknown value","unknown key2": "unknown value 2"} } ` json.Unmarshal([]byte(body), &t) fmt.Println(t.p) }
This code always returns an empty map.
You should export the structure fields that should be unmarshalled, for example:
type test struct { P map[string]string `json:"properties"` }
Seehttps://www.php.cn/link/eaf76caaba574ebf8e825f321c14ba29
The above is the detailed content of How to unmarshal json with unknown fields and keys. For more information, please follow other related articles on the PHP Chinese website!