Skip to content

Commit f22c2d3

Browse files
committed
badjson: Add Omitempty
1 parent ea9a9fa commit f22c2d3

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

common/json/badjson/merge.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88
"github.com/sagernet/sing/common/json"
99
)
1010

11-
func MergeOptions[T any](source T, destination T) (T, error) {
11+
func Merge[T any](source T, destination T) (T, error) {
1212
rawSource, err := json.Marshal(source)
1313
if err != nil {
1414
return common.DefaultValue[T](), E.Cause(err, "marshal source")
@@ -29,6 +29,27 @@ func MergeOptions[T any](source T, destination T) (T, error) {
2929
return merged, nil
3030
}
3131

32+
func Omitempty[T any](value T) (T, error) {
33+
objectContent, err := json.Marshal(value)
34+
if err != nil {
35+
return common.DefaultValue[T](), E.Cause(err, "marshal object")
36+
}
37+
rawNewObject, err := Decode(objectContent)
38+
if err != nil {
39+
return common.DefaultValue[T](), err
40+
}
41+
newObjectContent, err := json.Marshal(rawNewObject)
42+
if err != nil {
43+
return common.DefaultValue[T](), E.Cause(err, "marshal new object")
44+
}
45+
var newObject T
46+
err = json.Unmarshal(newObjectContent, &newObject)
47+
if err != nil {
48+
return common.DefaultValue[T](), E.Cause(err, "unmarshal new object")
49+
}
50+
return newObject, nil
51+
}
52+
3253
func MergeJSON(rawSource json.RawMessage, rawDestination json.RawMessage) (json.RawMessage, error) {
3354
source, err := Decode(rawSource)
3455
if err != nil {

0 commit comments

Comments
 (0)