Skip to content

Commit c48c8e7

Browse files
committed
badjson: Improve omitempty
1 parent 2175221 commit c48c8e7

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

common/json/badjson/array.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,25 @@ package badjson
33
import (
44
"bytes"
55

6+
"github.com/sagernet/sing/common"
67
E "github.com/sagernet/sing/common/exceptions"
78
"github.com/sagernet/sing/common/json"
89
)
910

1011
type JSONArray []any
1112

13+
func (a JSONArray) IsEmpty() bool {
14+
if len(a) == 0 {
15+
return true
16+
}
17+
return common.All(a, func(it any) bool {
18+
if valueInterface, valueMaybeEmpty := it.(isEmpty); valueMaybeEmpty && valueInterface.IsEmpty() {
19+
return true
20+
}
21+
return false
22+
})
23+
}
24+
1225
func (a JSONArray) MarshalJSON() ([]byte, error) {
1326
return json.Marshal([]any(a))
1427
}

common/json/badjson/empty.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package badjson
2+
3+
type isEmpty interface {
4+
IsEmpty() bool
5+
}

common/json/badjson/object.go

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,23 @@ type JSONObject struct {
1515
linkedhashmap.Map[string, any]
1616
}
1717

18-
func (m JSONObject) MarshalJSON() ([]byte, error) {
18+
func (m *JSONObject) IsEmpty() bool {
19+
if m.Size() == 0 {
20+
return true
21+
}
22+
return common.All(m.Entries(), func(it collections.MapEntry[string, any]) bool {
23+
if valueInterface, valueMaybeEmpty := it.Value.(isEmpty); valueMaybeEmpty && valueInterface.IsEmpty() {
24+
return true
25+
}
26+
return false
27+
})
28+
}
29+
30+
func (m *JSONObject) MarshalJSON() ([]byte, error) {
1931
buffer := new(bytes.Buffer)
2032
buffer.WriteString("{")
2133
items := common.Filter(m.Entries(), func(it collections.MapEntry[string, any]) bool {
22-
if valueObject, valueIsJSONObject := it.Value.(*JSONObject); valueIsJSONObject && valueObject.IsEmpty() {
34+
if valueInterface, valueMaybeEmpty := it.Value.(isEmpty); valueMaybeEmpty && valueInterface.IsEmpty() {
2335
return false
2436
}
2537
return true

0 commit comments

Comments
 (0)