douhuang2282 2017-12-11 06:42
浏览 208

无效的操作:类型接口{}不支持索引

I'm new to the golang and I have problem while reading the nested JSON response.

var d interface{}
json.NewDecoder(response.Body).Decode(&d)
test :=d["data"].(map[string]interface{})["type"]

response.Body looks like this

{
    "links": {
      "self": "/domains/test.one"
    },
    "data": {
        "type": "domains",
        "id": "test.one",
        "attributes": {
            "product": " Website",
            "package": "Professional",
            "created_at": "2016-08-19T11:37:01Z"
        }
    }
}

The Error I'm getting is this:

invalid operation: d["data"] (type interface {} does not support indexing)
  • 写回答

2条回答 默认 最新

  • dongnuoyi8833 2017-12-11 08:23
    关注

    You need some tricks to handle your situation.
    Like using reflect and you may ref Marshall&&UnMarshall code about bson.M in golang mongo driver mgo

    code sample using reflect decode nested as following:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "reflect"
    )
    
    func main() {
        keys := []string{"hello", "world", "dude", "kind", "cool"}
        a := make(map[string]interface{})
        a[keys[4]] = "perfect"
        b := make(map[string]interface{})
        b[keys[3]] = a
        c := make(map[string]interface{})
        c[keys[2]] = b
        d := make(map[string]interface{})
        d[keys[1]] = c
        e := make(map[string]interface{})
        e[keys[0]] = d
        fmt.Println(e)
    
        if buf, err := json.Marshal(e); nil == err {
            dd := make(map[string]interface{})
            err = json.Unmarshal(buf, &dd)
            if nil != err {
                fmt.Println("failed", err)
            }
    
            for k, v := range dd {
                travel(dd, k, v)
            }
            fmt.Println(dd)
    
        } else {
            fmt.Println("failed marshal")
        }
    }
    
    func travel(dd map[string]interface{}, key string, value interface{}) {
        vv := reflect.ValueOf(value)
        switch vv.Kind() {
        case reflect.Map:
            m := value.(map[string]interface{})
            dd[key] = m
            for k, v := range m {
                travel(m, k, v)
            }
        case reflect.String:
            dd[key] = value.(string)
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容