json - 解组并从 json 数组中获取第 n 项
问题描述
我想解组 JSON 并从人群中获取第二个名字“Andrey Borisenko”,
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)
推荐阅读
- node.js - 从 themoviedb API 检索数据
- css - 将 .scss 样式应用于 vuetify 自定义标签
- angularjs - 无法访问控制器 [angularJS] 内的 ng-model 值
- php - 如何更改linux xampp中的PHP路径?
- python - 从自定义路径中提取 .ppm.bz2 到自定义路径
- javascript - 移动动画后按钮悬停不再起作用
- go - 动态类型断言 Golang
- excel - 我正在尝试使用 VBA 宏将信息从 excel 电子表格写入 Powerpoint
- r - databricks 上的 sql sparklyr sparkr 数据帧转换
- orientdb - 使用 SQL 语言创建 onBeforeCreate 动态钩子