英文:
How to unmarshal json with unknown field and key
问题
从前端获取到了这个JSON示例:
{
"properties":{"unknown key": "unknown value","unknown key2": "unknown value 2"}
}
我开始使用map[string]interface{}
来解析它,但是不起作用。而且我不知道我可以获取到多少个这样的字段。可能是10个或者1个。
代码:
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)
}
这段代码总是返回一个空的map。
英文:
From front-end I got this example of json:
{
"properties":{"unknown key": "unknown value","unknown key2": "unknown value 2"}
}
I start to parse it with map[string]interface{} but it doesn't work. Also I don't know how much this fields I can got. It 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 return an empty map.
答案1
得分: 2
你应该导出需要解组的结构体字段,例如:
type test struct {
P map[string]string `json:"properties"`
}
参考链接:https://go.dev/play/p/Fp91DTlrZpw
英文:
You should export the field of the struct that should be Unmarshalled, like:
type test struct {
P map[string]string `json:"properties"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论