wrapper/easymap.go

89 lines
2.1 KiB
Go
Raw Normal View History

2023-08-10 15:19:06 +08:00
// Package wrapper ...
//
// Description : wrapper ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2023-08-10 15:01
package wrapper
import (
2023-08-10 16:58:13 +08:00
"encoding/json"
2023-08-10 15:19:06 +08:00
"errors"
"git.zhangdeman.cn/zhangdeman/easymap"
2023-10-12 18:50:56 +08:00
"git.zhangdeman.cn/zhangdeman/serialize"
2024-05-20 20:47:44 +08:00
"github.com/tidwall/gjson"
2023-08-10 15:19:06 +08:00
"reflect"
)
// EasyMap ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:02 2023/8/10
2024-11-06 18:29:18 +08:00
func EasyMap(mapData any) easymap.EasyMap {
2023-08-10 15:19:06 +08:00
m, _ := EasyMapWithError(mapData)
return m
}
// EasyMapWithError 转换map并带上转换的异常
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:06 2023/8/10
2024-11-06 18:29:18 +08:00
func EasyMapWithError(mapData any) (easymap.EasyMap, error) {
2023-08-27 14:40:13 +08:00
if nil == mapData {
2023-12-24 22:53:27 +08:00
return easymap.NewNormal(), nil
2023-08-27 14:40:13 +08:00
}
2023-12-24 22:53:27 +08:00
m := easymap.NewNormal()
2023-08-10 15:19:06 +08:00
reflectType := reflect.TypeOf(mapData)
if reflectType.Kind() != reflect.Map {
2024-06-08 20:06:35 +08:00
mapFormatData := make(map[string]any)
2024-10-24 21:52:51 +08:00
if err := serialize.JSON.UnmarshalWithNumber(serialize.JSON.MarshalForByteIgnoreError(mapData), &mapFormatData); nil != err {
2023-10-12 18:50:56 +08:00
return m, errors.New("input data type is " + reflectType.String() + ", can not convert to map")
}
mapData = mapFormatData
2023-08-10 15:19:06 +08:00
}
reflectValue := reflect.ValueOf(mapData).MapRange()
for reflectValue.Next() {
// 循环提取相关值
m.Set(reflectValue.Key().Interface(), reflectValue.Value().Interface())
}
return m, nil
}
2023-08-10 16:58:13 +08:00
// EasyMapFromStruct 从struct转map
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:11 2023/8/10
2024-11-06 18:29:18 +08:00
func EasyMapFromStruct(data any) easymap.EasyMap {
2023-08-10 16:58:13 +08:00
byteData, _ := json.Marshal(data)
return EasyMapFromByte(byteData)
}
// EasyMapFromString 从string转为Map
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:12 2023/8/10
2024-11-06 18:29:18 +08:00
func EasyMapFromString(data string) easymap.EasyMap {
2023-08-10 16:58:13 +08:00
return EasyMapFromByte([]byte(data))
}
// EasyMapFromByte 从字节数组转为Map
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:12 2023/8/10
2024-11-06 18:29:18 +08:00
func EasyMapFromByte(data []byte) easymap.EasyMap {
2024-05-20 20:47:44 +08:00
res := easymap.NewNormal()
jsonRes := gjson.Parse(string(data))
jsonRes.ForEach(func(key, value gjson.Result) bool {
res.Set(key.Value(), value.Value())
return true
})
return res
2023-08-10 16:58:13 +08:00
}