I have a piece of code that collects key/value store into json. Now key value store may contain array as a value, below is the json
{
"name":"abc",
"address":"some address value",
"phonenumber": "\"123123\",\"7897897\",\"45345345\""
}
and I want to unmarshal this to below struct
type myobj struct{
Name string `json:"name"`
Address string `json:"address`
PhoneNumbers []string
}
the phonenumbers field is a comma separated list in json, and I want to unmarshal this to an array of strings, how to I go about this?
You can unmarshal it to a string and then split it.
type myobj struct{
Name string `json:"name"`
Address string `json:"address`
PhoneNumberRaw string `json:"phonenumber"`
PhoneNumbers []string `json:"-"`
}
// Unmarshal.
var o myobj
json.Unmarshal(yourData, &o)
// Remove the quotes and split the phone number string by comma.
o.PhoneNumbers = strings.Split(strings.ReplaceAll(o.PhoneNumberRaw, `"`, ""), ",")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.