Home >Backend Development >Golang >How to Convert a Go Struct to a Map Using JSON Tags as Keys?
This question seeks a method to convert a Golang struct to a map, maintaining JSON tags as keys in the resulting map. Initially, the responses explored using the reflect package.
An alternative solution is provided by the structs package (https://github.com/fatih/structs) which offers comprehensive functions for working with structs:
The structs package supports anonymous fields and nested structs, and allows for filtering specific fields using field tags. For example:
type Server struct { Name string `json:"server_name"` ID int32 `json:"server_id"` Enabled bool `json:"is_enabled"` } s := &Server{ Name: "gopher", ID: 123456, Enabled: true, } // {"server_name": "gopher", "server_id": 123456, "is_enabled": true} m := structs.Map(s)
In this example, the json tags are used as map keys, producing a JSON-compliant map representation of the struct. The structs package provides a versatile tool for managing structs and converting them to maps, addressing the original request effectively.
The above is the detailed content of How to Convert a Go Struct to a Map Using JSON Tags as Keys?. For more information, please follow other related articles on the PHP Chinese website!