Search code examples
jsongotype-assertion

Simpler way to type assert a two-dimensional interface array from json unmarshal


I need to unmarshal a complex json data with a [][]interface{} array in it. I want to use more abstract struct type to unmarshal it, but Golang can only recognize it as []interface{}.

example code:

// I want to use this, but not work
var r1 = struct {
    Data map[string]interface{}
}{}

// Works well, but too complex if data nest much
var r2 = struct {
    Data struct{
        P1 int64
        P2 [][]interface{}
    }
}{}

jsonData := []byte(`{"data" :{"p1": 0, "p2":[["1", null], ["2", null] ]}}`)

json.Unmarshal (jsonData, &r1)
_, ok := r1.Data["p2"].([][]interface{})
fmt.Println(ok)

fmt.Println("======")

_, ok = r1.Data["p2"].([]interface{})
fmt.Println(ok)

fmt.Println("======")

json.Unmarshal (jsonData, &r2)
fmt.Println(r2.Data.P2)

output:

false
======
true
======
[[1 <nil>] [2 <nil>]]

Solution

  • Solution 1:

    You need to apply twice an assertion on your empty interface{} type.

    enter image description here

    https://play.golang.org/p/AeV6_fC3vYI