gjson/stringify.go

101 lines
2.2 KiB
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 gjson
import (
"encoding/json"
)
// Stringify 将JSONBaseObject转换为格式化的JSON字符串
// 类似于JavaScript中的JSON.stringify函数
func Stringify(obj JSONBaseObject, space ...string) (string, error) {
var indent string
if len(space) > 0 {
indent = space[0]
} else {
indent = "" // 默认无缩进
}
// 根据不同的对象类型进行处理
switch v := obj.(type) {
case *JSONObject:
if indent != "" {
// 格式化带缩进的JSON
bytes, err := json.MarshalIndent(v.data, "", indent)
if err != nil {
return "", err
}
return string(bytes), nil
} else {
// 紧凑型JSON
bytes, err := json.Marshal(v.data)
if err != nil {
return "", err
}
return string(bytes), nil
}
case *JSONArray:
if indent != "" {
// 格式化带缩进的JSON
bytes, err := json.MarshalIndent(v.data, "", indent)
if err != nil {
return "", err
}
return string(bytes), nil
} else {
// 紧凑型JSON
bytes, err := json.Marshal(v.data)
if err != nil {
return "", err
}
return string(bytes), nil
}
case *JSONString:
return v.ToJSON()
case *JSONNumber:
return v.ToJSON()
case *JSONBool:
return v.ToJSON()
case *JSONNull:
return v.ToJSON()
default:
// 如果是其他类型尝试转换为JSON
bytes, err := json.Marshal(v)
if err != nil {
return "", err
}
return string(bytes), nil
}
}
// StringifySimple 简单的字符串化函数将任何值转换为JSON字符串
func StringifySimple(value interface{}, space ...string) (string, error) {
var indent string
if len(space) > 0 {
indent = space[0]
} else {
indent = "" // 默认无缩进
}
if indent != "" {
bytes, err := json.MarshalIndent(value, "", indent)
if err != nil {
return "", err
}
return string(bytes), nil
} else {
bytes, err := json.Marshal(value)
if err != nil {
return "", err
}
return string(bytes), nil
}
}
// PrettyPrint 格式化打印JSON对象
func PrettyPrint(obj JSONBaseObject) (string, error) {
return Stringify(obj, " ") // 使用两个空格作为缩进
}
// Compact 将JSON对象转换为紧凑格式无多余空白字符
func Compact(obj JSONBaseObject) (string, error) {
return Stringify(obj) // 无缩进的格式
}