Home > Article > Backend Development > How to Unmarshal JSON Fields When They Are Strings Instead of Integers?
When dealing with JSON data, you may encounter situations where a JSON field is represented as a string instead of an integer, causing JSON Unmarshal to fail. This issue arises when JavaScript, which doesn't handle int64 values well, encodes JSON data.
Consider the following struct:
When you marshal this struct into JSON using the standard Marshal function and then modify the name field with jQuery before posting it back to your Go handler, the id field may be encoded as a string. This leads to an error when trying to unmarshal the JSON into a tySurvey struct:
To resolve this issue, you can specify that the id field can be unmarshaled from a string by adding ,string to the JSON tag:
This allows the JSON Unmarshal to successfully convert the string representation of the id field to an integer.
Note that setting omitempty on a field with ,string is not recommended, as the empty string cannot be unmarshaled into an integer.
The above is the detailed content of How to Unmarshal JSON Fields When They Are Strings Instead of Integers?. For more information, please follow other related articles on the PHP Chinese website!