Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go parse JSON array of array

Tags:

json

go

I have data like this

"descriptionMap": [[[1,2], "a"], [[3,4], "b"]]

and I was trying to decode it with

  DescriptionMap []struct {
    OpcodeTableIdPair []int
    OpcodeDescription string   
  } `json:"descriptionMap"`

but I keep on getting empty arrays,

[[{[] } {[] }]]
like image 201
Shulhi Sapli Avatar asked Apr 07 '26 07:04

Shulhi Sapli


1 Answers

You have a very unfortunate JSON schema which treats arrays as objects. The best you can do in this situation is something like this:

type Body struct {
    DescriptionMap []Description `json:"descriptionMap"`
}

type Description struct {
    IDPair      []int
    Description string
}

func (d *Description) UnmarshalJSON(b []byte) error {
    arr := []interface{}{}
    err := json.Unmarshal(b, &arr)
    if err != nil {
        return err
    }

    idPair := arr[0].([]interface{})
    d.IDPair = make([]int, len(idPair))
    for i := range idPair {
        d.IDPair[i] = int(idPair[i].(float64))
    }

    d.Description = arr[1].(string)

    return nil
}

Playground: https://play.golang.org/p/MPho12GJfc.

Notice though that this will panic if any of the types in the JSON don't match. You can create a better version which returns errors in such cases.

like image 116
Ainar-G Avatar answered Apr 10 '26 02:04

Ainar-G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!