diff --git a/pkg/stringx/strings.go b/pkg/stringx/strings.go index e95120e..2657aba 100644 --- a/pkg/stringx/strings.go +++ b/pkg/stringx/strings.go @@ -1,6 +1,7 @@ package stringx import ( + "encoding/json" "errors" "strings" ) @@ -119,3 +120,16 @@ func TakeOne(valid, or string) string { return or } + +// MustJsonString returns string from json.Marshal. +func MustJsonString(obj interface{}) string { + if obj == nil { + return "" + } + + b, err := json.Marshal(obj) + if err != nil { + return "" + } + return string(b) +} diff --git a/pkg/stringx/strings_test.go b/pkg/stringx/strings_test.go index 342daa3..a5a8520 100644 --- a/pkg/stringx/strings_test.go +++ b/pkg/stringx/strings_test.go @@ -297,3 +297,22 @@ func TestTakeOne(t *testing.T) { }) } } + +func TestMustJsonString(t *testing.T) { + tests := []struct { + name string + obj interface{} + want string + }{ + {"empty", "", `""`}, + {"nil", nil, ``}, + {"map", map[string]int{"a": 1}, `{"a":1}`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := MustJsonString(tt.obj); got != tt.want { + t.Errorf("MustJsonString() = %v, want %v", got, tt.want) + } + }) + } +}