首页 > 解决方案 > 解组并从 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])
}

标签: jsonparsinggo

解决方案


你的分配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)

用于现场游乐场


推荐阅读