Practice parsing json and nested structs

This commit is contained in:
raul 2024-04-28 10:13:51 +02:00
parent 3c56a83b0f
commit a6daa7b8e7
2 changed files with 66 additions and 0 deletions

3
urbdic/go.mod Normal file
View File

@ -0,0 +1,3 @@
module urbdic
go 1.22.2

63
urbdic/main.go Normal file
View File

@ -0,0 +1,63 @@
package main
import (
"encoding/json"
"fmt"
"log"
)
type people struct {
Example int `json:"number"`
personalDetails personalDetails
}
type personalDetails struct {
Name string `json:"name"`
}
func main() {
query := `
{
"message": "success",
"people": [
{
"name": "Jasmin Moghbeli",
"craft": "ISS"
},
{
"name": "Andreas Mogensen",
"craft": "ISS"
},
{
"name": "Satoshi Furukawa",
"craft": "ISS"
},
{
"name": "Konstantin Borisov",
"craft": "ISS"
},
{
"name": "Oleg Kononenko",
"craft": "ISS"
},
{
"name": "Nikolai Chub",
"craft": "ISS"
},
{
"name": "Loral O'Hara",
"craft": "ISS"
}
],
"number": 7
}`
textBytes := []byte(query)
urbDicRequest := people{}
err := json.Unmarshal(textBytes, &urbDicRequest)
if err != nil {
log.Fatalf("Error happened parsing json: %v\n", err)
}
fmt.Println(urbDicRequest.personalDetails.Name)
}