json unmarshal string or number to float64

2,334 views
Skip to first unread message

Michael Daffin

unread,
Feb 25, 2015, 9:09:30 AM2/25/15
to golan...@googlegroups.com
I has some json input that normally contains a string quoted float value but also some times take on the value of -1.


If I use 

Value float64 `json:"value"`

it errors with "json: cannot unmarshal string into Go value of type float64" for js1 and if I use

Value float64 `json:"value,string"`

it errors with "json: invalid use of ,string struct tag, trying to unmarshal unquoted value into [34 118 97 108 117 101 34]%!(EXTRA *reflect.rtype=main.R)" for js2.

What is the best way to convert both cases into float64 (or even the -1 to nil).

Note that this is happening for several values in a larger nested data structure so I want to avoid, if at all possible, copying all the values from interface{} into a new data structure of the correct types or casting interface{} every time I want to access the values.

Thank you

Ian Davis

unread,
Feb 25, 2015, 9:33:11 AM2/25/15
to golan...@googlegroups.com
You could use a custom type and implement the UnmarshalJSON interface for it. Something like:

Ian
 
Reply all
Reply to author
Forward
0 new messages