Skip to content
Snippets Groups Projects
Commit 24157f6b authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

2.14.28 - fixed a bug in JSONEncoder

parent 6c1c3137
No related branches found
Tags v2.14.28
No related merge requests found
# v2.14.28
* fixed a next bug in `JSONEncoder`
......@@ -5,6 +5,7 @@ Satella contains some expressions to help you with typing.
You import them from `satella.coding.typing`.
They are as follows:
* `NoneType` - the type of `None`
* `ExceptionClassType` - base type of exception class
* `Number` - an amalgam of int and float
* `T`, `U`, `K`, `V` - type vars to use
......
import typing as tp
from abc import ABCMeta, abstractmethod
NoneType = None.__class__
T = tp.TypeVar('T')
Iteratable = tp.Union[tp.Iterator[T], tp.Iterable[T]]
U = tp.TypeVar('U')
......
import json
import typing as tp
from abc import ABCMeta, abstractmethod
import typing
from satella.coding.typing import NoneType
try:
import ujson
except ImportError:
......@@ -28,6 +33,13 @@ class JSONEncoder(json.JSONEncoder):
def default(self, o: tp.Any) -> Jsonable:
if hasattr(o, 'to_json'):
return o.to_json()
elif isinstance(o, (int, float, str, NoneType)):
return o
elif isinstance(o, (list, tuple)):
return [self.default(v) for v in o]
elif isinstance(o, dict):
return {self.default(k): self.default(v) for k, v in o.items()}
try:
return super().default(o)
except TypeError:
......
......@@ -34,13 +34,15 @@ class TestJson(unittest.TestCase):
self.a = a
data = json.loads(json_encode(MyClass(5)))
self.assertEqual(data['a'], '5')
self.assertEqual(data['a'], 5)
class MyClass2:
__slots__ = ('a', )
__slots__ = ('a', 'b')
def __init__(self, a):
self.a = a
self.b = {'test': 'test2'}
data = json.loads(json_encode(MyClass2(5)))
self.assertEqual(data['a'], 5)
self.assertEqual(data['b']['test'], 'test2')
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment