Home > Backend Development > Golang > How to Map Strings to Diverse Types in Go JSON Objects?

How to Map Strings to Diverse Types in Go JSON Objects?

Barbara Streisand
Release: 2024-12-14 12:05:11
Original
718 people have browsed it

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:

  • Boolean values are stored as bool.
  • Numbers are stored as float64.
  • Strings are stored as string.
  • Arrays are stored as []interface{}.
  • Objects are stored as map[string]interface{}.
  • Null values are stored as nil.

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

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!

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