在 Golang 中访问类型 map[string]interface{} 的嵌套映射 [英] Accessing Nested Map of Type map[string]interface{} in Golang

查看:103
本文介绍了在 Golang 中访问类型 map[string]interface{} 的嵌套映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试解析 JSON 响应.它可以是多个级别的深度.这就是我所做的:

So I'm trying to parse a JSON response. It can be multiple levels deep. This is what I did:

var result map[string]interface{}
json.Unmarshal(apiResponse, &result)

首先,这是正确的做法吗?

假设响应如下:

{
  "args": {
            "foo": "bar"
          }
}

为了访问密钥 foo,我看到了一个 playground 这样做:

To access key foo, I saw a playground doing this:

result["args"].(map[string]interface{})["foo"]

这里,.() 符号是什么?这是正确的吗?

Here, what is the .() notation? Is this correct?

推荐答案

符号 x.(T) 被称为 类型断言.

对于接口类型的表达式x和类型T,主要表达式x.(T)断言x 不是 nil 并且存储在 x 中的值是 T 类型.

For an expression 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"]

这意味着与键 "args" 关联的 results 映射的值属于 map[string]interface{} (另一个带有 string 键和任何值的映射).并且您想访问与键 "foo" 关联的该映射的元素.

It means that the value of your 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".

如果您知道输入 JSON 格式,那么是的,您必须使用通用的 map[string]interface{} 类型来处理它.如果您知道输入 JSON 的确切结构,您可以创建一个 struct 来匹配预期的字段,这样您就可以将 JSON 文本解组为自定义 struct类型,例如:

If you know noting about the input JSON format, then yes, you have to use a generic 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}

Go Playground 上试试.

您当前的 JSON 输入可以使用这种类型建模:

Your current JSON input could be modelled with this type:

type Data struct {
    Args struct {
        Foo string
    }
}

并访问 Foo(在 Go Playground 上试试):

d := Data{}
json.Unmarshal([]byte(in), &d)
fmt.Println("Foo:", d.Args.Foo)

这篇关于在 Golang 中访问类型 map[string]interface{} 的嵌套映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆