Skip to content

Commit f4e10b0

Browse files
committed
moved json encoding into a utils file
1 parent 4496697 commit f4e10b0

File tree

3 files changed

+22
-17
lines changed

3 files changed

+22
-17
lines changed

piccolo/columns/column_types.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
)
1818
from piccolo.columns.defaults.uuid import UUIDArg, UUID4
1919
from piccolo.querystring import Unquoted, QueryString
20+
from piccolo.utils.encoding import dump_json
2021

2122
if t.TYPE_CHECKING:
2223
from piccolo.table import Table
@@ -1064,15 +1065,7 @@ def __init__(
10641065
self._validate_default(default, (str, list, dict, None))
10651066

10661067
if isinstance(default, (list, dict)):
1067-
# TODO - move to utils
1068-
try:
1069-
import orjson
1070-
except ImportError:
1071-
import json
1072-
1073-
default = json.dumps(default, default=str)
1074-
else:
1075-
default = orjson.dumps(default, default=str).decode("utf8")
1068+
default = dump_json(default)
10761069

10771070
self.default = default
10781071
kwargs.update({"default": default})

piccolo/query/base.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
from piccolo.querystring import QueryString
77
from piccolo.utils.sync import run_sync
8+
from piccolo.utils.encoding import dump_json
89

910
if t.TYPE_CHECKING:
1011
from piccolo.table import Table # noqa
@@ -68,14 +69,7 @@ async def _process_results(self, results):
6869
else:
6970
raw = list(itertools.chain(*[j.values() for j in raw]))
7071
if output._output.as_json:
71-
try:
72-
import orjson
73-
except ImportError:
74-
import json
75-
76-
raw = json.dumps(raw, default=str)
77-
else:
78-
raw = orjson.dumps(raw, default=str).decode("utf8")
72+
raw = dump_json(raw)
7973

8074
return raw
8175

piccolo/utils/encoding.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from __future__ import annotations
2+
import typing as t
3+
4+
try:
5+
import orjson
6+
7+
ORJSON = True
8+
except ImportError:
9+
import json
10+
11+
ORJSON = False
12+
13+
14+
def dump_json(data: t.Any) -> str:
15+
if ORJSON:
16+
return orjson.dumps(data, default=str).decode("utf8")
17+
else:
18+
return json.dumps(data, default=str)

0 commit comments

Comments
 (0)