goext/langext/json.go

114 lines
2.3 KiB
Go
Raw Permalink Normal View History

2022-10-27 16:48:26 +02:00
package langext
import (
"bytes"
"encoding/json"
"fmt"
)
type H map[string]any
type A []any
func TryPrettyPrintJson(str string) string {
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, []byte(str), "", " "); err != nil {
return str
}
return prettyJSON.String()
}
func PrettyPrintJson(str string) (string, bool) {
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, []byte(str), "", " "); err != nil {
return str, false
}
return prettyJSON.String(), true
}
func PatchJson[JV string | []byte](rawjson JV, key string, value any) (JV, error) {
var err error
var jsonpayload map[string]any
err = json.Unmarshal([]byte(rawjson), &jsonpayload)
if err != nil {
return *new(JV), fmt.Errorf("failed to unmarshal payload: %w", err)
}
jsonpayload[key] = value
newjson, err := json.Marshal(jsonpayload)
if err != nil {
return *new(JV), fmt.Errorf("failed to re-marshal payload: %w", err)
}
return JV(newjson), nil
}
func PatchRemJson[JV string | []byte](rawjson JV, key string) (JV, error) {
var err error
var jsonpayload map[string]any
err = json.Unmarshal([]byte(rawjson), &jsonpayload)
if err != nil {
return *new(JV), fmt.Errorf("failed to unmarshal payload: %w", err)
}
delete(jsonpayload, key)
newjson, err := json.Marshal(jsonpayload)
if err != nil {
return *new(JV), fmt.Errorf("failed to re-marshal payload: %w", err)
}
return JV(newjson), nil
}
2024-04-10 15:27:41 +02:00
func MarshalJsonOrPanic(v any) string {
bin, err := json.Marshal(v)
if err != nil {
panic(err)
}
return string(bin)
}
func MarshalJsonOrDefault(v any, def string) string {
bin, err := json.Marshal(v)
if err != nil {
return def
}
return string(bin)
}
func MarshalJsonOrNil(v any) *string {
bin, err := json.Marshal(v)
if err != nil {
return nil
}
return Ptr(string(bin))
}
2024-04-10 15:29:59 +02:00
func MarshalJsonIndentOrPanic(v any, prefix, indent string) string {
bin, err := json.MarshalIndent(v, prefix, indent)
if err != nil {
panic(err)
}
return string(bin)
}
func MarshalJsonIndentOrDefault(v any, prefix, indent string, def string) string {
bin, err := json.MarshalIndent(v, prefix, indent)
if err != nil {
return def
}
return string(bin)
}
func MarshalJsonIndentOrNil(v any, prefix, indent string) *string {
bin, err := json.MarshalIndent(v, prefix, indent)
if err != nil {
return nil
}
return Ptr(string(bin))
}