2023-07-21 17:07:04 +08:00
|
|
|
package jsonx
|
2021-06-07 17:22:07 +08:00
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
2023-09-02 17:24:18 +08:00
|
|
|
"mayfly-go/pkg/logx"
|
2023-07-22 20:51:46 +08:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
"github.com/buger/jsonparser"
|
2021-06-07 17:22:07 +08:00
|
|
|
)
|
|
|
|
|
|
2023-07-21 17:07:04 +08:00
|
|
|
// json字符串转map
|
|
|
|
|
func ToMap(jsonStr string) map[string]any {
|
2023-07-22 20:51:46 +08:00
|
|
|
return ToMapByBytes([]byte(jsonStr))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// json字节数组转map
|
|
|
|
|
func ToMapByBytes(bytes []byte) map[string]any {
|
2023-06-01 12:31:32 +08:00
|
|
|
var res map[string]any
|
2023-07-22 20:51:46 +08:00
|
|
|
err := json.Unmarshal(bytes, &res)
|
|
|
|
|
if err != nil {
|
2023-09-02 17:24:18 +08:00
|
|
|
logx.Errorf("json字符串转map失败: %s", err.Error())
|
2021-06-07 17:22:07 +08:00
|
|
|
}
|
|
|
|
|
return res
|
|
|
|
|
}
|
2023-02-13 21:11:16 +08:00
|
|
|
|
2023-07-21 17:07:04 +08:00
|
|
|
// 转换为json字符串
|
|
|
|
|
func ToStr(val any) string {
|
2023-02-13 21:11:16 +08:00
|
|
|
if strBytes, err := json.Marshal(val); err != nil {
|
2023-09-02 17:24:18 +08:00
|
|
|
logx.ErrorTrace("toJsonStr error: ", err)
|
2023-02-13 21:11:16 +08:00
|
|
|
return ""
|
|
|
|
|
} else {
|
|
|
|
|
return string(strBytes)
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-07-22 20:51:46 +08:00
|
|
|
|
|
|
|
|
// 根据json字节数组获取对应字段路径的string类型值
|
|
|
|
|
//
|
|
|
|
|
// @param fieldPath字段路径。如user.username等
|
|
|
|
|
func GetStringByBytes(bytes []byte, fieldPath string) (string, error) {
|
|
|
|
|
return jsonparser.GetString(bytes, strings.Split(fieldPath, ".")...)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 根据json字符串获取对应字段路径的string类型值
|
|
|
|
|
//
|
|
|
|
|
// @param fieldPath字段路径。如user.username等
|
|
|
|
|
func GetString(jsonStr string, fieldPath string) (string, error) {
|
|
|
|
|
return GetStringByBytes([]byte(jsonStr), fieldPath)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 根据json字节数组获取对应字段路径的int类型值
|
|
|
|
|
//
|
|
|
|
|
// @param fieldPath字段路径。如user.age等
|
|
|
|
|
func GetIntByBytes(bytes []byte, fieldPath string) (int64, error) {
|
|
|
|
|
return jsonparser.GetInt(bytes, strings.Split(fieldPath, ".")...)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 根据json字符串获取对应字段路径的int类型值
|
|
|
|
|
//
|
|
|
|
|
// @param fieldPath字段路径。如user.age等
|
|
|
|
|
func GetInt(jsonStr string, fieldPath string) (int64, error) {
|
|
|
|
|
return GetIntByBytes([]byte(jsonStr), fieldPath)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 根据json字节数组获取对应字段路径的bool类型值
|
|
|
|
|
//
|
|
|
|
|
// @param fieldPath字段路径。如user.isDeleted等
|
|
|
|
|
func GetBoolByBytes(bytes []byte, fieldPath string) (bool, error) {
|
|
|
|
|
return jsonparser.GetBoolean(bytes, strings.Split(fieldPath, ".")...)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 根据json字符串获取对应字段路径的bool类型值
|
|
|
|
|
//
|
|
|
|
|
// @param fieldPath字段路径。如user.isDeleted等
|
|
|
|
|
func GetBool(jsonStr string, fieldPath string) (bool, error) {
|
|
|
|
|
return GetBoolByBytes([]byte(jsonStr), fieldPath)
|
|
|
|
|
}
|