Home >Backend Development >Golang >How Can I Assign Multiple Data Types (String and Integer) to a Go Map for JSON Marshaling?

How Can I Assign Multiple Data Types (String and Integer) to a Go Map for JSON Marshaling?

Linda Hamilton
Linda HamiltonOriginal
2024-12-12 12:33:25368browse

How Can I Assign Multiple Data Types (String and Integer) to a Go Map for JSON Marshaling?

Assigning Multiple Types to Strings for JSON Objects

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn