doutuzhuohao6449 2018-05-03 09:06
浏览 42
已采纳

如何强制接口对象执行一些索引操作?

I got log data source looks like:

{"LogtypeA":{"content":"listen_logs":[{"useful_key1":val1,"useful_key2":val2},{"useful_key1":val1}]}}

Then I use simplejson to parse them. The value of listen_logs is a slice that contain at least one map. The code is:

for _, v := range js.Get("LogTypeA").Get("content").Get("listen_logs").MustArray() {
        _obj := reflect.ValueOf(v)
        fmt.Println(_obj.Kind())
    }

If I replace MustArray() with Array(), it will report incorrect variable and constant declarations. Using reflect module I will find that the _obj.Kind() is map, but I can't use any indexing method to get values from v such as:

_val1 := v["useful_key1"]

or

for i, v := range v {...}

Because type interface{} does not support indexing. So how should I extract those useful keyX from those logs?

  • 写回答

1条回答 默认 最新

  • duanba4942 2018-05-03 09:27
    关注

    You need to perform a type assertion on the resulting map:

    new_v := v.(map[string]interface{})
    _val1 := new_v["useful_key1"]
    

    Or, if you're not sure it will be a map:

    new_v, ok := v.(map[string]interface{})
    if ok {
        // it was a map from strings to something
        _val1 := new_v["useful_key1"]
    } else {
        print("Could not interpret v as a map.")
    }
    

    Since it's initially an empty interface, i.e. interface{}, that means it can be any type. So, you need to specify that you want to treat it as a map before trying to access the items.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入