gpt4 book ai didi

json - 解码并从 json 数组中获取第 n 项

转载 作者:行者123 更新时间:2023-12-01 22:32:50 24 4
gpt4 key购买 nike

我想解码 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)
For live playground

关于json - 解码并从 json 数组中获取第 n 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60006571/

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