为了账号安全,请及时绑定邮箱和手机立即绑定

迭代接口映射的值

迭代接口映射的值

Go
翻翻过去那场雪 2022-08-01 15:30:51
如何循环访问下面的接口映射以获取映射中返回的接口值?我已经通读了有关Go迭代的大量问题列表,但它们没有帮助我。// https://api.kraken.com/0/public/AssetPairspairsResult, err := api.Query("AssetPairs", map[string]string{})if err != nil {    log.Fatal(err)}ks := reflect.ValueOf(pairsResult).MapKeys()fmt.Printf(" %+v ", pairsResult) // result A belowfmt.Printf(" %+v ", ks) // result B below// the value here is the value of MapKeys, which is the keyfor kix, key := range ks {    fmt.Printf(" %+v %+v \n ", kix, key) // result C below}结果 Amap[AAVEETH:map[aclass_base:currency aclass_quote:currency altname:AAVEeth base:AAVE fee_volume_currency:ZUSD fee:[[0 0.26] [50000 0.24] [100000 0.22] [250000 0.2] [500000 0.18]...结果 B[KEEPXBT LINKUSD LINKXBT NANOEUR ...]结果 C0 KEEPXBT 1 LINKUSD 2 LINKXBT 3 NANOEUR 4 USDTAUD ...这是上面调用的 API 包装器函数的源// Query sends a query to Kraken api for given method and parametersfunc (api *KrakenAPI) Query(method string, data map[string]string) (interface{}, error) {    values := url.Values{}    for key, value := range data {        values.Set(key, value)    }    // Check if method is public or private    if isStringInSlice(method, publicMethods) {        return api.queryPublic(method, values, nil)    } else if isStringInSlice(method, privateMethods) {        return api.queryPrivate(method, values, nil)    }    return nil, fmt.Errorf("Method '%s' is not valid", method)}
查看完整描述

2 回答

?
繁花如伊

TA贡献2012条经验 获得超12个赞

假设您正在使用它,并且通过查看其来源,在我看来,结果的具体类型将是 ,如果是这种情况,那么您可以执行此操作。map[string]interface{}


res, err := api.Query("AssetPairs", map[string]string{})

if err != nil {

    log.Fatal(err)

}


pairs, ok := res.(map[string]interface{})

if !ok {

    log.Fatal("unsupported type")

}


for k, v := range pairs {

    fmt.Printf("key=%s value=%+v\n ", k, v)

}



查看完整回答
反对 回复 2022-08-01
?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

正如前面的响应中提到的,我们看到返回的接口变成了map[string]interface{},下面的代码将执行检索类型的技巧:


    for _, v := range d.(map[string]interface{}) {

        switch v.(type) {

        case map[string]interface{}:

            fmt.Println("Its another map of string interface")

        case interface{}:

            fmt.Println("its an interface")

        case string:

            fmt.Println("its a string")

        case []string:

            fmt.Println("its a string array")

        case float32:

            fmt.Println("its a float32")

        case float64:

            fmt.Println("its a float64")

        default:

            fmt.Printf("Different thing, %T\n", v)

        }

    }


此处代码: https://play.golang.org/p/81LLYSvJVf8


但是,我建议使用显式类型,这将使您的生活更加轻松:


// Generated by https://quicktype.io


type KrakenTypes struct {

    Error  []interface{}     `json:"error"` 

    Result map[string]Result `json:"result"`

}


type Result struct {

    Altname           string            `json:"altname"`            

    Wsname            *string           `json:"wsname,omitempty"`   

    AclassBase        Aclass            `json:"aclass_base"`        

    Base              string            `json:"base"`               

    AclassQuote       Aclass            `json:"aclass_quote"`       

    Quote             FeeVolumeCurrency `json:"quote"`              

    Lot               Lot               `json:"lot"`                

    PairDecimals      int64             `json:"pair_decimals"`      

    LotDecimals       int64             `json:"lot_decimals"`       

    LotMultiplier     int64             `json:"lot_multiplier"`     

    LeverageBuy       []int64           `json:"leverage_buy"`       

    LeverageSell      []int64           `json:"leverage_sell"`      

    Fees              [][]float64       `json:"fees"`               

    FeesMaker         [][]float64       `json:"fees_maker"`         

    FeeVolumeCurrency FeeVolumeCurrency `json:"fee_volume_currency"`

    MarginCall        int64             `json:"margin_call"`        

    MarginStop        int64             `json:"margin_stop"`        

    Ordermin          *string           `json:"ordermin,omitempty"` 

}

在这里,我们可以在读取响应后使用json解码,因此可以避免迭代以找出每个级别的类型,并且我们可以直接访问每个成员。


此处的完整代码:https://play.golang.org/p/v3tlroyx1mW


查看完整回答
反对 回复 2022-08-01
  • 2 回答
  • 0 关注
  • 78 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信