Skip to content

Commit e43b2c0

Browse files
committed
chore: optimize json dump
1 parent 245dff8 commit e43b2c0

File tree

4 files changed

+19
-12
lines changed

4 files changed

+19
-12
lines changed

src/genpac/format/pac.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
import json
2-
31
from ..template import TemplateFile
4-
from ..util import conv_bool
2+
from ..util import conv_bool, dump_json
53
from .base import formater, FmtBase
64

75
_TPL_PAC = TemplateFile('res/tpl-pac.js', True)
@@ -42,7 +40,7 @@ def pre_generate(self):
4240
return super().pre_generate()
4341

4442
def generate(self, replacements):
45-
rules = json.dumps(
43+
rules = dump_json(
4644
self.precise_rules if self.options.precise else self.rules,
4745
indent=None if self.options.compress else 4,
4846
separators=(',', ':') if self.options.compress else None)

src/genpac/format/sing_box.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
import json
2-
3-
from ..util import conv_lower, Namespace
1+
from ..util import conv_lower, Namespace, dump_json
42
from .base import formater
53
from .ip import IPInterface, _IP_FAMILIES, _CC_DEF
64

@@ -30,4 +28,4 @@ def generate(self, replacements):
3028
data.rules.append({
3129
'ip_cidr': [str(d) for d in self.iter_ip_cidr(self.options.ip_family, self.options.ip_cc)]
3230
})
33-
return json.dumps(dict(data), indent=2)
31+
return dump_json(data)

src/genpac/format/v2ray.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
1-
import json
2-
31
from ..util import dump_yaml
4-
from ..util import conv_lower
2+
from ..util import conv_lower, dump_json
53
from .base import formater, FmtBase, TPL_LEAD_COMMENT
64

7-
V2RAY_DUMPER = {'json': lambda d: json.dumps(d, indent=4),
5+
V2RAY_DUMPER = {'json': lambda d: dump_json(d),
86
'yaml': lambda d: f'{TPL_LEAD_COMMENT}\n' + dump_yaml(d)}
97
_DEF_FORMAT = list(V2RAY_DUMPER.keys())[0]
108
_DEF_PROXY_TAG = 'proxy'

src/genpac/util.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,19 @@ def dump_yaml(data, **kwargs):
5959
return yaml.dump(data, **kwargs)
6060

6161

62+
class JSONEncoder(json.JSONEncoder):
63+
def default(self, o):
64+
if isinstance(o, Namespace):
65+
return dict(o)
66+
return super().default(o)
67+
68+
69+
def dump_json(data, **kwargs):
70+
kwargs.setdefault('indent', 2)
71+
kwargs.setdefault('cls', JSONEncoder)
72+
return json.dumps(data, **kwargs)
73+
74+
6275
class Error(Exception):
6376
def __init__(self, msg):
6477
self.msg = msg

0 commit comments

Comments
 (0)