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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动