我查看了许多有关如何使用 go 解析 JSON 的示例,并且了解了基础知识。但是我无法获得要正确解析的对象数组。我已经为该对象创建了一个结构,但没有骰子!
这是一个关于它的 Playground : <知识库> playground
package main
import (
"encoding/json"
"fmt"
)
type Outer struct {
Number int `json: "number"`
Message string `json: "message"`
Person []Person `json: "person"`
}
type Person struct {
craft string `json: "craft"`
name string `json: "name"`
}
func main() {
text := `{"people": [{"craft": "ISS", "name": "Sergey Rizhikov"}, {"craft": "ISS", "name": "Andrey Borisenko"}, {"craft": "ISS", "name": "Shane Kimbrough"}, {"craft": "ISS", "name": "Oleg Novitskiy"}, {"craft": "ISS", "name": "Thomas Pesquet"}, {"craft": "ISS", "name": "Peggy Whitson"}], "message": "success", "number": 6}`
textBytes := []byte(text)
people1 := Outer{}
err := json.Unmarshal(textBytes, &people1)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(people1)
}
最佳答案
你的代码有几个错误:
- 您在 json 中有
people
字段,但在结构声明中有person
。 Person
结构字段必须以大写字母开头。- 删除 json 标签中的空格
json:"name"
有效而json: "name"
无效。
这是固定的 version.
关于json - 从 JSON 解析嵌套对象数组到 Go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48555622/