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 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b