如何解析具有未知字段和键的 JSON 数据?

huangapple go评论87阅读模式
英文:

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"`
}

See https://go.dev/play/p/Fp91DTlrZpw

huangapple
  • 本文由 发表于 2023年1月10日 16:22:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75067228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定