0

I need to parse an interface read from a JSON object which is deeply nested. I use the following recursive function to get most of the array.

func arrayReturn(m map[string]interface{}) []interface{} {
    for _, v:= range m {
        if v.(type) == map[string]interface{} {
            return arrayReturn(v.(map[string]interface{}))
        }
        if v.(type) == string {
            return v.([]interface{})
        } 
    }
}

Which gives this error for the return line:

syntax error: unexpected return, expecting expression

What does "expecting expression" mean?

1 Answer 1

5

This syntax:

if v.(type) == map[string]interface{} { /* ... */ }

is invalid. You can't compare to a type, only to a value.

What you want may be solved using a type switch, where the cases are indeed types:

func arrayReturn(m map[string]interface{}) []interface{} {
    for _, v := range m {
        switch v2 := v.(type) {
        case map[string]interface{}:
            return arrayReturn(v2)     // v2 is of type map[string]interface{}
        case []interface{}:
            return v2                  // v2 is of type []interface{}
        }
    }
    return nil
}

Also note that if you use a short variable declaration after the switch keyword, in each case the type of the variable used will be what you specify in the case, so no further type assertion is needed!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.