I need to parse json into a struct in golang and the final value is a float64
But it seems that some inputs encode it as a string and some encode it as a float64
This is across a lot of variables so I would rather not make a custom function for each field
What is the best way to do this in golang?
I know the json tags can let values be stored as strings, but now that I am receiving raw floats it is starting to error out
This is a parsing FROM json only operation, so I do not care about what it implies or makes impossible for encoding TO json
Example code:
type Example struct {
var1 float64 `json:"var1"`
}
func main() {
var ex Example
json.Unmarshal([]byte("{"var1":10.0}", &ex)
json.Unmarshal([]byte("{"var1":"10.0"}", &ex)
}
2
Answers
Create a type that unmarshals a JSON string or JSON number to a float64.
Use it like this:
https://go.dev/play/p/-ubMyX93Tdj
Understanding the Problem
The challenge is to parse JSON where a field, intended to be a
float64
, can appear as either a float or a string.Solutions
Go’s built-in json.Number is often sufficient for handling numeric JSON values:
For complex scenarios or ultimate control, implement a custom unmarshaling method:
How it Works:
Key Improvements:
Choosing a Solution:
UnmarshalJSON
method shines.