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

How to Efficiently Convert a Go Struct to a Map Using JSON Tags?

Susan Sarandon
Release: 2024-12-11 18:41:10
Original
245 people have browsed it

How to Efficiently Convert a Go Struct to a Map Using JSON Tags?

Function for Converting a Struct to a Map in Golang

Question:

How can I efficiently convert a struct to a map in Golang, utilizing JSON tags as keys where possible?

Answer:

Third-Party Library:

The structs package by Fatih provides a straightforward and comprehensive solution for this task:

func Map(object interface{}) map[string]interface{}
Copy after login

Usage:

package main

import (
    "fmt"

    "github.com/fatih/structs"
)

type Server struct {
    Name    string `json:"name"`
    ID      int32  `json:"id"`
    Enabled bool   `json:"enabled"`
}

func main() {
    s := &Server{
        Name:    "gopher",
        ID:      123456,
        Enabled: true,
    }

    m := structs.Map(s)
    fmt.Println(m) // Output: {"name":"gopher", "id":123456, "enabled":true}
}
Copy after login

Features:

  • Supports anonymous and nested structs
  • Uses JSON tags for keys
  • Allows filtering of fields using tags

Custom Implementation:

If a custom implementation is preferred, reflect.Struct can be utilized:

func ConvertToMap(model interface{}) map[string]interface{} {
    // Get the reflect type and value of the model
    modelType := reflect.TypeOf(model)
    modelValue := reflect.ValueOf(model)
    
    if modelValue.Kind() == reflect.Ptr {
        modelValue = modelValue.Elem()
    }
    
    // Check if the model is a struct
    if modelType.Kind() != reflect.Struct {
        return nil
    }
    
    // Create a new map to store the key-value pairs
    ret := make(map[string]interface{})
    
    // Iterate over the fields of the struct
    for i := 0; i < modelType.NumField(); i++ {
        // Get the field and its name
        field := modelType.Field(i)
        fieldName := field.Name
        
        // Check if the field has a JSON tag
        jsonTag := field.Tag.Get("json")
        if jsonTag != "" {
            fieldName = jsonTag
        }
        
        // Get the value of the field
        fieldValue := modelValue.Field(i)
        
        // Recursively convert nested structs
        switch fieldValue.Kind() {
        case reflect.Struct:
            ret[fieldName] = ConvertToMap(fieldValue.Interface())
        default:
            ret[fieldName] = fieldValue.Interface()
        }
    }
    
    return ret
}
Copy after login

However, this requires manually extracting the field names and converting nested structs.

The above is the detailed content of How to Efficiently Convert a Go Struct to a Map Using JSON Tags?. 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