gpt4 book ai didi

json - 数组上的 Golang json 解码失败

转载 作者:数据小太阳 更新时间:2023-10-29 03:39:13 26 4
gpt4 key购买 nike

我有一个像这样的对象:

   a = [{
"name": "rdj",
"place": "meh",
"meh" : ["bow", "blah"]
}]

我定义了这样一个结构:

type first struct {
A []one
}

type one struct {
Place string `json: "place"`
Name string `json: "name"`
}

当我在代码中使用相同的代码时:

func main() {
res, _ := http.Get("http://127.0.0.1:8080/sample/")
defer res.Body.Close()
var some first
rd := json.NewDecoder(res.Body)
err := rd.Decode(&some)
errorme(err)
fmt.Printf("%+v\n", some)
}

我收到以下错误:

panic: json: cannot unmarshal array into Go value of type main.first

我的理解是:

type first 定义数组,该数组中是 type one 中定义的数据结构。

最佳答案

JSON 是一个对象数组。使用这些类型:

type one struct {   // Use struct for JSON object
Place string `json: "place"`
Name string `json: "name"`
}

...

var some []one // Use slice for JSON array
rd := json.NewDecoder(res.Body)
err := rd.Decode(&some)

问题中的类型匹配这个 JSON 结构:

{"A": [{
"name": "rdj",
"place": "meh",
"meh" : ["bow", "blah"]
}]}

关于json - 数组上的 Golang json 解码失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40873562/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com