kra/pkg/utils/json.go

49 lines
920 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package utils
import (
"encoding/json"
"strings"
)
// GetJSONKeys 获取JSON对象的所有键保持顺序
func GetJSONKeys(jsonStr string) (keys []string, err error) {
dec := json.NewDecoder(strings.NewReader(jsonStr))
t, err := dec.Token()
if err != nil {
return nil, err
}
// 确保数据是一个对象
if t != json.Delim('{') {
return nil, err
}
for dec.More() {
t, err = dec.Token()
if err != nil {
return nil, err
}
keys = append(keys, t.(string))
// 解析值
var value interface{}
err = dec.Decode(&value)
if err != nil {
return nil, err
}
}
return keys, nil
}
// ToJSON 将对象转换为JSON字符串
func ToJSON(v interface{}) string {
b, err := json.Marshal(v)
if err != nil {
return ""
}
return string(b)
}
// FromJSON 将JSON字符串解析为对象
func FromJSON(jsonStr string, v interface{}) error {
return json.Unmarshal([]byte(jsonStr), v)
}