Mike Schwörer
2e713c808d
Some checks failed
Build Docker and Deploy / Run goext test-suite (push) Failing after 1m10s
114 lines
2.3 KiB
Go
114 lines
2.3 KiB
Go
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
|
|
}
|
|
|
|
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))
|
|
}
|
|
|
|
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))
|
|
}
|