Skip to content

Commit

Permalink
badjson: Add Omitempty
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Dec 6, 2023
1 parent f44931b commit c18e182
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion common/json/badjson/merge.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/sagernet/sing/common/json"
)

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

func Omitempty[T any](value T) (T, error) {
objectContent, err := json.Marshal(value)
if err != nil {
return common.DefaultValue[T](), E.Cause(err, "marshal object")
}
rawNewObject, err := Decode(objectContent)
if err != nil {
return common.DefaultValue[T](), err
}
newObjectContent, err := json.Marshal(rawNewObject)
if err != nil {
return common.DefaultValue[T](), E.Cause(err, "marshal new object")
}
var newObject T
err = json.Unmarshal(newObjectContent, &newObject)
if err != nil {
return common.DefaultValue[T](), E.Cause(err, "unmarshal new object")
}
return newObject, nil
}

func MergeJSON(rawSource json.RawMessage, rawDestination json.RawMessage) (json.RawMessage, error) {
source, err := Decode(rawSource)
if err != nil {
Expand Down

0 comments on commit c18e182

Please sign in to comment.