Parsing nested JSON using nested structs

This commit is contained in:
raul 2024-04-29 08:38:25 +02:00
parent a6daa7b8e7
commit 81b210b338
2 changed files with 14 additions and 8 deletions

View File

@ -4,15 +4,16 @@ import (
"encoding/json"
"fmt"
"log"
"os"
"strconv"
)
type people struct {
Example int `json:"number"`
personalDetails personalDetails
}
type personalDetails struct {
Name string `json:"name"`
PersonalDetails []struct {
Name string `json:"name"`
Craft string `json:"craft"`
} `json:"people"`
}
func main() {
@ -46,11 +47,12 @@ func main() {
},
{
"name": "Loral O'Hara",
"craft": "ISS"
"craft": "Test"
}
],
"number": 7
}`
}
`
textBytes := []byte(query)
urbDicRequest := people{}
err := json.Unmarshal(textBytes, &urbDicRequest)
@ -58,6 +60,10 @@ func main() {
log.Fatalf("Error happened parsing json: %v\n", err)
}
fmt.Println(urbDicRequest.personalDetails.Name)
choicString := os.Args[1]
choice, _ := strconv.Atoi(choicString)
fmt.Println(urbDicRequest.PersonalDetails[choice].Name)
fmt.Println(urbDicRequest.PersonalDetails[choice].Craft)
}