如何获取一个嵌套在另一个映射中的值?

huangapple go评论79阅读模式
英文:

How i can get a value that is inside a map, inside other map?

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我是golang的新手,我遇到了这个问题。

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"]
	}
}

我想要使用"Age"的值做一些事情,我该如何做到这一点?

英文:

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 ?

答案1

得分: 0

interface{} 类型中的值可以是任何类型的值。在访问之前,使用 类型断言 来确保值的类型对于操作是有效的:

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)

}
英文:

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)

}

huangapple
  • 本文由 发表于 2022年4月9日 10:30:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/71804837.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定