Skip to content

Commit a507ec3

Browse files
add json_serialize in utils
1 parent d7cad83 commit a507ec3

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

pysenal/utils/utils.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import os
33
import copy
44
from collections import Iterable
5+
from decimal import Decimal
56

67

78
def get_chunk(l, n):
@@ -111,3 +112,24 @@ def index(l, val, default=-1):
111112
return default
112113
else:
113114
return l.index(val)
115+
116+
117+
def json_serialize(obj):
118+
"""
119+
add serialize method used in json.dumps or json.dump
120+
:param obj: input obj
121+
:return: string representation for json.dump or json.dumps
122+
"""
123+
if isinstance(obj, Decimal):
124+
numerator, denumerator = obj.as_integer_ratio()
125+
if denumerator == 1:
126+
return str(numerator)
127+
else:
128+
return str(obj)
129+
elif isinstance(obj, bytes):
130+
return str(obj)
131+
else:
132+
try:
133+
return str(obj)
134+
except:
135+
raise TypeError(repr(obj) + ' is not JSON serializable')

tests/utils/test_utils.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import shutil
33
import tempfile
44
from types import GeneratorType
5+
from decimal import Decimal
56
import pytest
67
from pysenal.utils.utils import *
78

@@ -103,4 +104,11 @@ def test_index():
103104
assert index(values, 6) == -1
104105
assert index(values, 6, default=100) == 100
105106
with pytest.raises(TypeError):
106-
index(10,10)
107+
index(10, 10)
108+
109+
110+
def test_json_serialize():
111+
assert json_serialize(Decimal('3.1415926')) == '3.1415926'
112+
assert json_serialize(Decimal('11.0')) == '11'
113+
assert json_serialize(b'123') == "b'123'"
114+
assert json_serialize(11) == '11'

0 commit comments

Comments
 (0)