Go 구조체를 map으로 변환

개요[ | ]

Go 구조체를 map으로 변환
package main

import (
	"fmt"
	"reflect"
)

type Address struct {
	Street string
	City   string
}

type Person struct {
	Name    string
	Age     int
	Address Address
	Friends []string
}

func StructToMap(input any) map[string]any {
	output := make(map[string]any)
	val := reflect.ValueOf(input)
	typ := reflect.TypeOf(input)

	if val.Kind() == reflect.Ptr {
		val = val.Elem()
		typ = typ.Elem()
	}

	for i := 0; i < val.NumField(); i++ {
		fieldName := typ.Field(i).Name
		fieldValue := val.Field(i)

		switch fieldValue.Kind() {
		case reflect.Struct:
			output[fieldName] = StructToMap(fieldValue.Interface())
		case reflect.Slice:
			slice := make([]any, fieldValue.Len())
			for j := 0; j < fieldValue.Len(); j++ {
				elem := fieldValue.Index(j)
				if elem.Kind() == reflect.Struct {
					slice[j] = StructToMap(elem.Interface())
				} else {
					slice[j] = elem.Interface()
				}
			}
			output[fieldName] = slice
		default:
			output[fieldName] = fieldValue.Interface()
		}
	}

	return output
}

func main() {
	person := Person{
		Name: "Alice",
		Age:  30,
		Address: Address{
			Street: "123 Main St",
			City:   "New York",
		},
		Friends: []string{"Bob", "Charlie", "David"},
	}

	result := StructToMap(person)
	fmt.Println(result)
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}