2024-01-27 14:36:14 +08:00
|
|
|
package convutil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type JsonConvert struct{}
|
|
|
|
|
2024-02-20 10:55:46 +08:00
|
|
|
func (JsonConvert) Enable() bool {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2024-01-27 14:36:14 +08:00
|
|
|
func (JsonConvert) Decode(str string) (string, bool) {
|
|
|
|
trimedStr := strings.TrimSpace(str)
|
|
|
|
if (strings.HasPrefix(trimedStr, "{") && strings.HasSuffix(trimedStr, "}")) ||
|
|
|
|
(strings.HasPrefix(trimedStr, "[") && strings.HasSuffix(trimedStr, "]")) {
|
|
|
|
var out bytes.Buffer
|
|
|
|
if err := json.Indent(&out, []byte(trimedStr), "", " "); err == nil {
|
|
|
|
return out.String(), true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return str, false
|
|
|
|
}
|
|
|
|
|
|
|
|
func (JsonConvert) Encode(str string) (string, bool) {
|
|
|
|
var dst bytes.Buffer
|
|
|
|
if err := json.Compact(&dst, []byte(str)); err != nil {
|
|
|
|
return str, false
|
|
|
|
}
|
|
|
|
return dst.String(), true
|
|
|
|
}
|