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" "encoding/json"
"fmt" "fmt"
"log" "log"
"os"
"strconv"
) )
type people struct { type people struct {
Example int `json:"number"` Example int `json:"number"`
personalDetails personalDetails PersonalDetails []struct {
}
type personalDetails struct {
Name string `json:"name"` Name string `json:"name"`
Craft string `json:"craft"`
} `json:"people"`
} }
func main() { func main() {
@ -46,11 +47,12 @@ func main() {
}, },
{ {
"name": "Loral O'Hara", "name": "Loral O'Hara",
"craft": "ISS" "craft": "Test"
} }
], ],
"number": 7 "number": 7
}` }
`
textBytes := []byte(query) textBytes := []byte(query)
urbDicRequest := people{} urbDicRequest := people{}
err := json.Unmarshal(textBytes, &urbDicRequest) err := json.Unmarshal(textBytes, &urbDicRequest)
@ -58,6 +60,10 @@ func main() {
log.Fatalf("Error happened parsing json: %v\n", err) 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)
} }