Home >Backend Development >Golang >How to Map Strings to Diverse Types in Go JSON Objects?
Mapping Strings to Diverse Types in JSON Objects
In Go, maps require specifying their key and value types explicitly. When dealing with JSON objects, which permit key-value pairs of arbitrary types, this restriction poses a hurdle.
Question:
How can we create a map that can be converted into a JSON object of the form { "a": "apple", "b": 2 }, where keys and values can be of different types?
Answer:
Go provides a solution through its interface{} type, which can hold values of any type. According to the encoding/json package documentation, when unmarshaling JSON into an interface{}, the following rules apply:
To utilize this, we can simply create a map[string]interface{} and populate it with values of different types:
m := map[string]interface{}{"a":"apple", "b":2}
This map can now be easily converted into a JSON object by marshalling it using the json.Marshal() function.
The above is the detailed content of How to Map Strings to Diverse Types in Go JSON Objects?. For more information, please follow other related articles on the PHP Chinese website!