I want to unmarshal an array of json object into a struct. Each json object has a json array for one of the properties. If the property is defined as a string, works. If it's defined as an array of byte or string, I get an error.
I have tried a number of approaches but keep getting an error.
panic: ERROR: json: cannot unmarshal string into Go struct field
.productlist of type []string
Source file:
{
"orgs": [
{
"orgname": "Test Organization 26",
"orgs_id": 26,
"contactdate": "2019-12-12",
"sincedate": "2019-12-12",
"estusers": null,
"estvehicles": null,
"paidusers": null,
"paythreshold": null,
"productlist": "[\"SDCC\",\"JOB_CARDS\",\"ALLOCATIONS\"]",
"roles": "[\"DISPATCH\",\"DRIVERS\",\"MECHANICS\"]"
}
]
}
Go Struct:
type OrgsJSONData struct {
Orgs []struct {
Orgname string `json:"orgname"`
OrgsID int `json:"orgs_id"`
Contactdate string `json:"contactdate"`
Sincedate string `json:"sincedate"`
Estusers interface{} `json:"estusers"`
Estvehicles interface{} `json:"estvehicles"`
Paidusers interface{} `json:"paidusers"`
Paythreshold interface{} `json:"paythreshold"`
Productlist []string `json:"productlist"`
Roles string `json:"roles"`
} `json:"orgs"`
}
Code:
var orgsJSONData OrgsJSONData
tmp := []byte(strings.Join(JsonData, ""))
err := json.Unmarshal(tmp, &orgsJSONData)
if err != nil {
panic("ERROR: " + err.Error())
}
If the productlist property is a string, the unmarshal works. If it is any other slice or array, I get the error "panic: ERROR: json: cannot unmarshal string into Go struct field .productlist of type []string" What am I doing wrong. P.S. Very new to Golang (Week 2 and learning)
The productlist field in the JSON input is a string, not an array:
"productlist": "[\"SDCC\",\"JOB_CARDS\",\"ALLOCATIONS\"]"
Note that the contents of it are quoted, and enclosed quotes are escaped. This is a string, not an array.
If it was an array, it would have been:
"productlist": ["SDCC","JOB_CARDS","ALLOCATIONS"]