Skip to content

Commit

Permalink
chore: optimize json dump
Browse files Browse the repository at this point in the history
  • Loading branch information
JinnLynn committed Jul 22, 2024
1 parent 245dff8 commit e43b2c0
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 12 deletions.
6 changes: 2 additions & 4 deletions src/genpac/format/pac.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import json

from ..template import TemplateFile
from ..util import conv_bool
from ..util import conv_bool, dump_json
from .base import formater, FmtBase

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

def generate(self, replacements):
rules = json.dumps(
rules = dump_json(
self.precise_rules if self.options.precise else self.rules,
indent=None if self.options.compress else 4,
separators=(',', ':') if self.options.compress else None)
Expand Down
6 changes: 2 additions & 4 deletions src/genpac/format/sing_box.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import json

from ..util import conv_lower, Namespace
from ..util import conv_lower, Namespace, dump_json
from .base import formater
from .ip import IPInterface, _IP_FAMILIES, _CC_DEF

Expand Down Expand Up @@ -30,4 +28,4 @@ def generate(self, replacements):
data.rules.append({
'ip_cidr': [str(d) for d in self.iter_ip_cidr(self.options.ip_family, self.options.ip_cc)]
})
return json.dumps(dict(data), indent=2)
return dump_json(data)
6 changes: 2 additions & 4 deletions src/genpac/format/v2ray.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import json

from ..util import dump_yaml
from ..util import conv_lower
from ..util import conv_lower, dump_json
from .base import formater, FmtBase, TPL_LEAD_COMMENT

V2RAY_DUMPER = {'json': lambda d: json.dumps(d, indent=4),
V2RAY_DUMPER = {'json': lambda d: dump_json(d),
'yaml': lambda d: f'{TPL_LEAD_COMMENT}\n' + dump_yaml(d)}
_DEF_FORMAT = list(V2RAY_DUMPER.keys())[0]
_DEF_PROXY_TAG = 'proxy'
Expand Down
13 changes: 13 additions & 0 deletions src/genpac/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,19 @@ def dump_yaml(data, **kwargs):
return yaml.dump(data, **kwargs)


class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, Namespace):
return dict(o)
return super().default(o)


def dump_json(data, **kwargs):
kwargs.setdefault('indent', 2)
kwargs.setdefault('cls', JSONEncoder)
return json.dumps(data, **kwargs)


class Error(Exception):
def __init__(self, msg):
self.msg = msg
Expand Down

0 comments on commit e43b2c0

Please sign in to comment.