dougong7850 2014-04-09 15:25
浏览 31
已采纳

遍历Golang地图

I initialized a variable named data like this:

   var data interface{}

Then I unmarshalled raw json into.

   err = json.Unmarshal(raw, &data)

I've run these two functions on it:

   fmt.Println(reflect.TypeOf(data))
   fmt.Println(data)

and those return this:

   map[string]interface {}
   map[tasks:[map[payload:map[key:36A6D454-FEEE-46EB-9D64-A85ABEABBCB7] code_name:image_resize]]]

and I need to access the "key". I have tried these approaches and a few more:

   data["tasks"][0]["payload"]["key"]
   data[0][0][0][0]

Those have all given me an error similar to this one:

    ./resize.go:44: invalid operation: data["tasks"] (index of type interface {})

Any advice on how to grab the "key" value out of this interface? Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dongtan7418 2014-04-09 16:08
    关注

    Since you already know your schema, the best way to do this is to unmarshal directly into structs you can use.

    http://play.golang.org/p/aInZp8IZQA

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type msg struct {
        Tasks []task `json:"tasks"`
    }
    
    type task struct {
        CodeName string  `json:"code_name"`
        Payload  payload `json:"payload"`
    }
    
    type payload struct {
        Key string `json:"key"`
    }
    
    func main() {
        var data msg
        raw := `{ "tasks": [ { "code_name": "image_resize", "payload": { "key": "36A6D454-FEEE-46EB-9D64-A85ABEABBCB7" } } ] }`
    
        err := json.Unmarshal([]byte(raw), &data)
        if err != nil {
            fmt.Println(err)
            return
        }
    
        fmt.Println(data.Tasks[0].Payload.Key)
    }
    

    If you insist on doing things the hard way using your original code, you need to do type assertions. I highly recommend avoiding this route when possible. It is not fun. Every step needs to be checked to ensure it matches the data structure you expect.

    http://play.golang.org/p/fI5sqKV19J

    if m, ok := data.(map[string]interface{}); ok {
        if a, ok := m["tasks"].([]interface{}); ok && len(a) > 0 {
            if e, ok := a[0].(map[string]interface{}); ok {
                if p, ok := e["payload"].(map[string]interface{}); ok {
                    if k, ok := p["key"].(string); ok {
                        fmt.Println("The key is:", k)
                    }
                }
            }
        }
    }
    

    In response to Goodwine's question: You can read further about how to marshal and unmarshal by reading the encoding/json godoc. I suggest starting here:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应