在Golang中访问类型为map [string] interface {}的嵌套映射 [英] Accessing Nested Map of Type map[string]interface{} in Golang
问题描述
$ $ p $ $ code var结果图字符串接口
json.Unmarshal(apiResponse,& amp; amp; ;结果)
首先,这是正确的方法吗?
假设回应如下:
{
args:{
foo:bar
}
}
要访问 foo
键,我看到一个 playground 这样做:
result [args]。(map [string] interface {} )[foo]
这里,。()
符号?这是正确的吗?
符号 x。(T)
是称为类型断言。
对于接口类型和类型
T
的表达式x
,主表达式x。(T)
断言x
不是nil
,并且存储在x
中的值是类型T
。
您的示例:
result [args]。(map [string] interface {} )[foo]
这意味着的结果
map关键字args
的类型是 string
键和任何值的映射)。并且你想访问与关键字foo
关联的那张地图的元素。
如果您知道注意事项关于输入的JSON格式,那么是的,你必须使用一个通用的 map [string]接口{}
类型来处理它。如果您知道输入JSON的确切结构,您可以创建一个 struct
来匹配预期的字段,这样您可以将JSON文本解组为一个您自定义的值 struct
类型,例如:
类型Point结构{
名称字符串
X,Y int
}
func main(){
in:=`{Name:center,X: 2,Y:3}`
pt:= Point {}
json.Unmarshal([] byte(in),& pt)
fmt.Printf(Result:%+ v,pt)
}
输出:
结果:{姓名:中心X:2 Y:3}
在 Go Playground 。
为输入建模
您可以使用此类型对当前的JSON输入进行建模:
类型数据结构{
Args结构{
Foo字符串
}
}
访问 So I'm trying to parse a JSON response. It can be multiple levels deep. This is what I did: Firstly, is this the right way to do it? Lets say the response was as follows: To access key Here, what is the The notation For an expression Your example: It means that the value of your If you know noting about the input JSON format, then yes, you have to use a generic Output: Try it on the Go Playground. Your current JSON input could be modelled with this type: And accessing
这篇关于在Golang中访问类型为map [string] interface {}的嵌套映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! Foo
(在
d:= Data {}
json.Unmarshal([ ]字节(in),& d)
fmt.Println(Foo:,d.Args.Foo)
var result map[string]interface{}
json.Unmarshal(apiResponse, &result)
{
"args": {
"foo": "bar"
}
}
foo
, I saw a playground doing this:result["args"].(map[string]interface{})["foo"]
.()
notation? Is this correct?x.(T)
is called a Type Assertion.
x
of interface type and a type T
, the primary expression x.(T)
asserts that x
is not nil
and that the value stored in x
is of type T
.result["args"].(map[string]interface{})["foo"]
results
map associated with key "args"
is of type map[string]interface{}
(another map with string
keys and any values). And you want to access the element of that map associated with the key "foo"
.map[string]interface{}
type to process it. If you know the exact structure of the input JSON, you can create a struct
to match the expected fields, and doing so you can unmarshal a JSON text into a value of your custom struct
type, for example:type Point struct {
Name string
X, Y int
}
func main() {
in := `{"Name":"center","X":2,"Y":3}`
pt := Point{}
json.Unmarshal([]byte(in), &pt)
fmt.Printf("Result: %+v", pt)
}
Result: {Name:center X:2 Y:3}
Modeling your input
type Data struct {
Args struct {
Foo string
}
}
Foo
(try it on the Go Playground):d := Data{}
json.Unmarshal([]byte(in), &d)
fmt.Println("Foo:", d.Args.Foo)