Files
EdgeAdmin/internal/utils/json.go

61 lines
1.1 KiB
Go
Raw Permalink Normal View History

2024-05-17 17:56:37 +08:00
// Copyright 2022 GoEdge CDN goedge.cdn@gmail.com. All rights reserved.
2022-03-04 17:00:01 +08:00
package utils
import (
"bytes"
2022-03-04 17:00:01 +08:00
"encoding/json"
"errors"
2022-03-04 17:00:01 +08:00
"reflect"
)
// JSONClone 使用JSON克隆对象
func JSONClone(v interface{}) (interface{}, error) {
data, err := json.Marshal(v)
if err != nil {
return nil, err
}
var nv = reflect.New(reflect.TypeOf(v).Elem()).Interface()
err = json.Unmarshal(data, nv)
if err != nil {
return nil, err
}
return nv, nil
}
// JSONIsNull 判断JSON数据是否为null
func JSONIsNull(jsonData []byte) bool {
return len(jsonData) == 0 || bytes.Equal(jsonData, []byte("null"))
}
// JSONDecodeConfig 解码并重新编码
// 是为了去除原有JSON中不需要的数据
func JSONDecodeConfig(data []byte, ptr any) (encodeJSON []byte, err error) {
err = json.Unmarshal(data, ptr)
if err != nil {
return
}
encodeJSON, err = json.Marshal(ptr)
if err != nil {
return
}
// validate config
if ptr != nil {
config, ok := ptr.(interface {
Init() error
})
if ok {
initErr := config.Init()
if initErr != nil {
err = errors.New("validate config failed: " + initErr.Error())
}
}
}
return
}