Issue
I’ve the following struct and i want to loop over a slice embedded in it :
package main
import (
"encoding/json"
"fmt"
)
var input = `[
{
"Country_Name": "USA",
"Cities": ["city_1","city_2"]
},{
"Country_Name": "UK",
"Cities": ["city_1","city_2"]
}
] `
func main() {
var prop []struct {
CountryName string `json:"Country_Name"`
Cities []string `json:"Cities"`
}
if err := json.Unmarshal([]byte(input), &prop); err != nil {
panic(err)
}
for _, field := range prop {
fmt.Printf("Country_Name : %s\n", field.CountryName)
}
}
That’s to get Cities
fields
Any help for that , Thank you in advance
Solution
Perhaps I’m missing something, but why not just:
for _, field := range prop {
fmt.Printf("Country_Name : %s\n", field.CountryName)
for _, city := range field.Cities {
fmt.Printf("City: %s\n", city)
}
}
Answered By – Shay Nehmad
Answer Checked By – Cary Denson (GoLangFix Admin)