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

changed the behaviour of JSONEncoder

parent 28bc3664
No related branches found
No related tags found
No related merge requests found
# v2.4.17 # v2.4.17
* _TBA_ * changed the behaviour of `JSONEncoder` when it comes to serializing unknown objects
# v2.4.16 # v2.4.16
......
...@@ -17,3 +17,8 @@ You might also want to check out the JSONEncoder satella uses to do it. ...@@ -17,3 +17,8 @@ You might also want to check out the JSONEncoder satella uses to do it.
.. autoclass:: satella.json.JSONEncoder .. autoclass:: satella.json.JSONEncoder
:members: :members:
This will serialize unknown objects in the following way.
First, **__dict__** will be extracted out of this object. The dictionary
will be constructed in such a way, that for each key in this **__dict__**,
it's value's **repr** will be assigned.
...@@ -21,7 +21,10 @@ class JSONEncoder(json.JSONEncoder): ...@@ -21,7 +21,10 @@ class JSONEncoder(json.JSONEncoder):
try: try:
return super().default(o) return super().default(o)
except TypeError: except TypeError:
return {'type': repr(type(o)), 'str': str(o), 'repr': repr(o)} dct = {}
for k, v in o.__dict__.items():
dct[k] = repr(v)
return dct
def json_encode(x) -> str: def json_encode(x) -> str:
......
import typing as tp import typing as tp
import unittest import unittest
import sys
import json
from satella.json import JSONAble, json_encode from satella.json import JSONAble, json_encode
...@@ -15,6 +17,8 @@ class TestJson(unittest.TestCase): ...@@ -15,6 +17,8 @@ class TestJson(unittest.TestCase):
def test_unjsonable_objects(self): def test_unjsonable_objects(self):
class MyClass: class MyClass:
pass def __init__(self, a):
self.a = a
json_encode(MyClass()) data = json.loads(json_encode(MyClass(5)))
self.assertEqual(data['a'], '5')
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