如何解析 map[string]interface{} 类型的数据?

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

How to parse map[string]interface{}

问题

我无法解析具有字符串键和数组值的 JSON,最终导致 json: Unmarshal(non-pointer map[string]interface {}) 错误。

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. func main() {
  7. var s map[string]interface{}
  8. err := json.Unmarshal([]byte(`{"a":[1,2,3]}`), &s)
  9. if err != nil {
  10. panic(err)
  11. }
  12. fmt.Println("解析成功!")
  13. }

https://go.dev/play/p/AXlF8I-f9-p

英文:

I am unable to parse json that has string keys and array as value ending up with json: Unmarshal(non-pointer map[string]interface {}) error.

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. func main() {
  7. var s map[string]interface{}
  8. err := json.Unmarshal([]byte("{\"a\":[1,2,3]}"), s)
  9. if err != nil {
  10. panic(err)
  11. }
  12. fmt.Println("Nice parse!")
  13. }

https://go.dev/play/p/AXlF8I-f9-p

答案1

得分: 4

Unmarshal函数解析JSON编码的数据,并将结果存储在指向v的值中。如果v为nil或不是指针类型,Unmarshal函数将返回一个InvalidUnmarshalError错误。将&s作为参数添加进去。

err := json.Unmarshal([]byte("{"a":[1,2,3]}"), &s)

英文:

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError. Add &s as a parameter

  1. err := json.Unmarshal([]byte("{\"a\":[1,2,3]}"), &s)

huangapple
  • 本文由 发表于 2021年12月3日 02:23:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/70204634.html
匿名

发表评论

匿名网友

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

确定