From 81b210b3389db5c426a3e13b26feb5bf532d90df Mon Sep 17 00:00:00 2001 From: raul Date: Mon, 29 Apr 2024 08:38:25 +0200 Subject: [PATCH] Parsing nested JSON using nested structs --- {urbdic => parseJSON}/go.mod | 0 {urbdic => parseJSON}/main.go | 22 ++++++++++++++-------- 2 files changed, 14 insertions(+), 8 deletions(-) rename {urbdic => parseJSON}/go.mod (100%) rename {urbdic => parseJSON}/main.go (71%) diff --git a/urbdic/go.mod b/parseJSON/go.mod similarity index 100% rename from urbdic/go.mod rename to parseJSON/go.mod diff --git a/urbdic/main.go b/parseJSON/main.go similarity index 71% rename from urbdic/main.go rename to parseJSON/main.go index d1f60a9..958cd62 100644 --- a/urbdic/main.go +++ b/parseJSON/main.go @@ -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) }