Q: Seeking a method to construct a map that translates to a JSON object with both string and integer values, such as:
{ "a": "apple", "b": 2 }
However, Go mandates type-specified maps, leaving developers with options like map[string]string or map[string]int.
A: Utilize Go's interface{} type to store arbitrary data types. As documented in the encoding/json package:
When JSON unmarshals into an interface value, it stores appropriate concrete types based on the JSON content: - bool for booleans - float64 for numbers - string for strings - []interface{} for arrays - map[string]interface{} for objects - nil for null
To implement this solution:
m := map[string]interface{}{"a":"apple", "b":2}
The above is the detailed content of How Can I Assign Multiple Data Types (String and Integer) to a Go Map for JSON Marshaling?. For more information, please follow other related articles on the PHP Chinese website!