doukanwen4114 2018-08-11 19:52 采纳率: 100%
浏览 66
已采纳

项目列表的Golang类型断言

Im calling a API and it returns a dictionary(map) with a list of items as values.

For ex:-

result= {'outputs':[{'state':'md','country':'us'}, {'state':'ny','country':'ny'}]}

The above data is how the data represented in python.

In Python, I directly use result['outputs'][0] to access the list of elements in the list.

In Golang, the same API returns the data but when I try to access the data as result['outputs'][0]

Get this error:-

invalid operation: result["outputs"][0] (type interface {} does not support indexing)

Looks like I need to do a type conversion, what should I use to type convert, I tried this

result["outputs"][0].(List)
result["outputs"][0].([])

but both throws me an error.

I checked the type of the returned item and this is it - []interface {}

What should be my type conversion?

  • 写回答

1条回答 默认 最新

  • duanshan1511 2018-08-11 20:13
    关注

    You wrote the type of the value is []interface{}, so then do a type assertion asserting that type.

    Also note that you first have to type assert, and index later, e.g.:

    outputs := result["outputs"].([]interface{})
    
    firstOutput := outputs[0]
    

    Also note that the (static) type of firstOutput will again be interface{}. To access its content, you will need another type assertion, most likely a map[string]interface{} or a map[interface{}]interface{}.

    If you can, model your data with structs so you don't have to do this "type assertion nonsense".

    Also note that there are 3rd party libs that support easy "navigation" inside dynamic objects such as yours. For one, there's github.com/icza/dyno (disclosure: I'm the author).

    Using dyno, getting the first output would be like:

    firstOutput, err := dyno.Get(result, "outputs", 0)
    

    To get the country of the first output:

    country, err := dyno.Get(result, "outputs", 0, "country")
    

    You can also "reuse" previously looked up values, like this:

    firstOutput, err := dyno.Get(result, "outputs", 0)
    // check error
    country, err := dyno.Get(firstOutput, "country")
    // check error
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失