'How i can get a value that is inside a map, inside other map? [duplicate]
I'm newbie in golang and I have this problem.
package main
import "fmt"
func main() {
Problem := map[string]interface{}{
"Alan": map[string]interface{}{
"Particulars": map[string]interface{}{
"Age": "28",
},
},
"Sophia": map[string]interface{}{
"Particulars": map[string]interface{}{
"Age": "18",
},
},
}
Ages := []string{}
for key, value := range Problem {
fmt.Println(key)
fmt.Println(value)
Ages = value["Age"]
}
}
I want to use the valor of "Age" for something, how I can do this ?
Solution 1:[1]
A value in interface{} type can be any type of value. Use a type assertion to ensure the value type is valid for the operation before accessing it:
package main
import "fmt"
func main() {
Problem := map[string]interface{}{
"Alan": map[string]interface{}{
"Particulars": map[string]interface{}{
"Age": "28",
},
},
"Sophia": map[string]interface{}{
"Particulars": map[string]interface{}{
"Age": "18",
},
},
}
Ages := []string{}
for key, value := range Problem {
fmt.Println(key)
fmt.Println(value)
a, ok := value.(map[string]interface{})["Particulars"].(map[string]interface{})["Age"].(string)
if ok {
Ages = append(Ages, a)
}
}
fmt.Println(Ages)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cyril |
