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

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

How to parse map[string]interface{}

问题

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

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	var s map[string]interface{}
	err := json.Unmarshal([]byte(`{"a":[1,2,3]}`), &s)
	if err != nil {
		panic(err)
	}
	fmt.Println("解析成功!")
}

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.

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	var s map[string]interface{}
	err := json.Unmarshal([]byte("{\"a\":[1,2,3]}"), s)
	if err != nil {
		panic(err)
	}
	fmt.Println("Nice parse!")
}

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

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:

确定