Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I iterate over the map of interfaces below to get the values of the interface returned in the map?

I have read through the extensive list of questions regarding iteration in Go but they didn't help me.

// https://api.kraken.com/0/public/AssetPairs

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

if err != nil {
    log.Fatal(err)
}

ks := reflect.ValueOf(pairsResult).MapKeys()

fmt.Printf(" %+v ", pairsResult) // result A below
fmt.Printf(" %+v ", ks) // result B below

// the value here is the value of MapKeys, which is the key
for kix, key := range ks {
    fmt.Printf(" %+v %+v 
 ", kix, key) // result C below
}

Result A

map[AAVEETH:map[aclass_base:currency aclass_quote:currency altname:AAVEETH base:AAVE fee_volume_currency:ZUSD fees:[[0 0.26] [50000 0.24] [100000 0.22] [250000 0.2] [500000 0.18]...

Result B

[KEEPXBT LINKUSD LINKXBT NANOEUR ...]

Result C

0 KEEPXBT 1 LINKUSD 2 LINKXBT 3 NANOEUR 4 USDTAUD ...

This is the source of the API wrapper function that is being called above

// Query sends a query to Kraken api for given method and parameters
func (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)
}

This happens when I try to iterate over the value:

Iterate over value

This happens when I try to iterate over the initial result:

Iterate over result

question from:https://stackoverflow.com/questions/65651604/iterate-over-values-of-map-of-interfaces

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
327 views
Welcome To Ask or Share your Answers For Others

1 Answer

Assuming you're using this and from looking a bit into its source it seems to me that the concrete type of the result will be map[string]interface{}, if that is the case then you can do this.

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
 ", k, v)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...