Accessing Nested Map of Type map[string]interface{} in Golang

The notation x.(T) is called a Type Assertion.

For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T.

Your example:

result["args"].(map[string]interface{})["foo"]

It means that the value of your results map associated with key "args" is of type map[string]interface{} (another map with string keys and any values). And you want to access the element of that map associated with the key "foo".

If you know noting about the input JSON format, then yes, you have to use a generic map[string]interface{} type to process it. If you know the exact structure of the input JSON, you can create a struct to match the expected fields, and doing so you can unmarshal a JSON text into a value of your custom struct type, for example:

type Point struct {
    Name string
    X, Y int
}

func main() {
    in := `{"Name":"center","X":2,"Y":3}`

    pt := Point{}
    json.Unmarshal([]byte(in), &pt)

    fmt.Printf("Result: %+v", pt)
}

Output:

Result: {Name:center X:2 Y:3}

Try it on the Go Playground.

Modeling your input

Your current JSON input could be modelled with this type:

type Data struct {
    Args struct {
        Foo string
    }
}

And accessing Foo (try it on the Go Playground):

d := Data{}
json.Unmarshal([]byte(in), &d)
fmt.Println("Foo:", d.Args.Foo)

Leave a Comment