I am trying to unmarshal the custom type Percent from a string. When I run the code below, I get the following error: Error: invalid character '%' after top-level value. I assumed that I would have at least hit the UnmarshalJSON method, but it does not.
type Percent float32
func (p *Percent) UnmarshalJSON(data []byte) error {
fmt.Println("Unmarshalling Percent")
s := strings.TrimRight(strings.TrimRight(string(data), "%"), " ")
v, err := strconv.ParseFloat(s, 32)
if err != nil {
return err
}
*p = Percent(v)
return nil
}
func main() {
s := "50%"
var p Percent
err := json.Unmarshal([]byte(s), &p)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Parsed Percent:", p)
}
}
