我想解组 JSON 并从人群中获取第二个名字"安德烈鲍里森科",
杰森:
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}`
到目前为止我的代码:
package main
import (
"fmt"
"encoding/json"
)
type people struct {
NAME string `json:"craft"`
}
func main() {
const 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 := people{}
err := json.Unmarshal(textBytes, &people1)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(people1.NAME.[1])
}
你对json.Unmarshal
和结构的赋值不利于你想做的事情。
你的结构应该看起来像这样:
type myStruct struct {
Peoples []struct {
Craft string `json:"craft"`
Name string `json:"name"`
} `json:"people"`
}
这将为您提供一系列人员(Peoples
(
for _, eachOne := range peopleStruct.Peoples {
fmt.Println(eachOne.Name) //eachOne.Name == name of you guys
fmt.Println(eachOne.Craft) //eachOne.Craft == craft of you guys
}
对于安德烈:fmt.Println(peopleStruct.Peoples[1].Name)
对于现场游乐场