douba4275 2015-03-02 10:00
浏览 334
已采纳

在Golang中访问类型为map [string] interface {}的嵌套地图

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)

Firstly, is this the right way to do it?

Lets say the response was as follows:

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

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

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

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

  • 写回答

1条回答 默认 最新

  • dsjbest2015 2015-03-02 10:11
    关注

    The notation x.(T) is called a Type Assertion.

    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.

    Your example:

    result["args"].(map[string]interface{})["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".

    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)
    }
    

    Output:

    Result: {Name:center X:2 Y:3}
    

    Try it on the Go Playground.

    Modeling your input

    Your current JSON input could be modelled with this type:

    type Data struct {
        Args struct {
            Foo string
        }
    }
    

    And accessing Foo (try it on the Go Playground):

    d := Data{}
    json.Unmarshal([]byte(in), &d)
    fmt.Println("Foo:", d.Args.Foo)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。