[go] struct to map 변환 하기

2021. 4. 2. 15:15golang

// []struct 형태를 map 으로 변환
func ArrMap(arr interface{}) map[int]map[string]interface{} {
	entries := make(map[int]map[string]interface{})
	if arr == nil {
		return entries
	}

	items := reflect.ValueOf(arr)
	if items.Kind() == reflect.Slice {
		for i := 0; i < items.Len(); i++ {
			item := items.Index(i)
			if entries[i] == nil {
				entries[i] = make(map[string]interface{})
			}
			if item.Kind() == reflect.Struct {
				v := reflect.Indirect(item)

				for j := 0; j < v.NumField(); j++ {
					tag := v.Type().Field(j).Tag.Get("json")
					// fmt.Println(v.Type().Field(j).Name, v.Field(j).Interface())
					entries[i][tag] = v.Field(j).Interface()
				}
			}
		}
	}
	return entries
}
// struct 형태를 map으로 변환
func Map(item interface{}) map[string]interface{} {
	res := map[string]interface{}{}
	if item == nil {
		return res
	}
	v := reflect.TypeOf(item)
	reflectValue := reflect.ValueOf(item)
	reflectValue = reflect.Indirect(reflectValue)

	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}
	for i := 0; i < v.NumField(); i++ {
		tag := v.Field(i).Tag.Get("json")
		field := reflectValue.Field(i).Interface()
		if tag != "" && tag != "-" {
			if v.Field(i).Type.Kind() == reflect.Struct {
				res[tag] = Map(field)
			} else {
				res[tag] = field
			}
		}
	}
	return res
}

'golang' 카테고리의 다른 글

Go mysql에서 mysql error num 추출  (0) 2021.03.26