Home > Backend Development > Golang > How to Convert a Go Struct to a Map Using JSON Tags as Keys?

How to Convert a Go Struct to a Map Using JSON Tags as Keys?

Linda Hamilton
Release: 2024-12-09 20:54:15
Original
210 people have browsed it

How to Convert a Go Struct to a Map Using JSON Tags as Keys?

Converting Struct to Map in Golang with JSON 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:

  • ConvertToMap: Converts a struct to a map
  • ExtractFields: Obtains a slice of field names from a struct
  • ExtractValues: Extracts a slice of field values from a struct
  • IsStruct: Checks if a provided interface is a struct or a pointer to a struct
  • IsInitialized: Verifies if a struct is initialized

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

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!

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