mitchellh / mapstructure

Go library for decoding generic map values into native Go structures and vice versa.
https://gist.github.com/mitchellh/90029601268e59a29e64e55bab1c5bdc
MIT License
7.89k stars 669 forks source link

Unable to decode single-dimension json array #308

Open AlastairDewar opened 2 years ago

AlastairDewar commented 2 years ago

Hello,

I've come across and issue where when trying to convert a Gorm Model, which has a field of gorm.io/datatypes/JSON, and a value similar to ["a", "b", "c"].

It looks as though the assignment of the fieldType variable on line 1310 of mapstructure.go using reflection is incorrectly returning an integer type, and not a string. Given the ability to have json arrays with [1, "2"] - it might be better just to allow for a an interface{} when looking at arrays/json?

The resultant output is

2022/10/07 10:49:49 Unable to decode MyObject object: 5 error(s) decoding:

* 'my_field[0]' expected type 'uint8', got unconvertible type 'string', value: 'a'
* 'my_field[1]' expected type 'uint8', got unconvertible type 'string', value: 'b'
* 'my_field[2]' expected type 'uint8', got unconvertible type 'string', value: 'c'

Example Gorm Model

type Video struct {
    ID             uint           `gorm:"primaryKey; type:bigint; not null;" json:"id"`
    MyField   datatypes.JSON `gorm:"type:jsonb;default:'[]';" json:"my_field" mapstructure:"my_field"`
    CreatedAt      time.Time      `json:"created_at"`
    UpdatedAt      time.Time      `json:"updated_at"`
}

All the best, Ally