How can I call len () on an interface?

I am writing a test that the JSON list is empty.

{"matches": []}

The object is of type map[string]interface{}and I want to check that the list is empty.

var matches := response["matches"]
if len(matches) != 0 {
    t.Errorf("Non-empty match list!")
}

However, at compile time they tell me that this is not true

invalid argument matches (type interface {}) for len

If I try to apply to a list type:

matches := response["matches"].([]string)

I get a panic:

panic: interface conversion: interface is []interface {}, not []string [recovered]

What do I want to write here?

+4
source share
1 answer

Parsing JSON with maps in Go uses interfaces everywhere. Imagine you have the following JSON object:

{
    "stuff" : [
        "stuff1",
        "stuff2",
        "stuff3",
    ]
}

Go JSON , . , . , , , interface{}. , , "stuff", , . :

arr := myMap["stuff"]

, , :

arr := myMap["stuff"].([]interface{})

, , , , JSON , , string, []string. , :

{
    "stuff" : [
        "stuff1",
        "stuff2",
        3
    ]
}

"stuff" , . - - , . , Go JSON , []interface{}. , , , , . :

arr := myMap["stuff"].([]interface{})
l := len(arr)

, , , . , , , :

arr := myMap["stuff"].([]interface{})
iv := arr[0] // interface value
sv := iv.(string) // string value

"", JSON - JSON. , Go, "" ( Go , - - , C Java, Go ).

+11

All Articles