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
Release: 2024-12-12 12:33:25
Original
288 people have browsed it

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
}
Copy after login

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
Copy after login

To implement this solution:

m := map[string]interface{}{"a":"apple", "b":2}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template