+33
-6
lines changedFilter options
+33
-6
lines changed Original file line number Diff line number Diff line change
@@ -1,27 +1,54 @@
1
+
"""
2
+
This module defines the main mechanism to extend the JSON format.
3
+
"""
4
+
1
5
__version__ = "0.1.1"
2
6
3
7
import json
4
8
5
9
6
10
class ExtendedEncoder(json.JSONEncoder):
7
-
def default(self, obj):
8
-
name = type(obj).__name__
11
+
"""JSON encoder defining the mechanism to encode arbitrary Python objects.
12
+
13
+
To encode an arbitrary object, you should subclass this encoder and define one
14
+
encode_X method for each type of object you want to be able to encode.
15
+
The method name should start with "encode_" and end with the type name.
16
+
The method accepts the given type of Python object and
17
+
should return a JSON-serialisable dictionary with the appropriate data,
18
+
which typically amounts to the data necessary to rebuild the object later on.
19
+
A related decoder must be implemented if decoding from JSON is required.
20
+
"""
21
+
22
+
def default(self, o):
23
+
name = type(o).__name__
9
24
try:
10
25
encoder = getattr(self, f"encode_{name}")
11
26
except AttributeError:
12
-
super().default(obj)
27
+
return super().default(o)
13
28
else:
14
-
encoded = encoder(obj)
29
+
encoded = encoder(o)
15
30
encoded["__extended_json_type__"] = name
16
31
return encoded
17
32
18
33
19
34
class ExtendedDecoder(json.JSONDecoder):
35
+
"""JSON decoder defining the mechanism to decode arbitrary JSON objects.
36
+
37
+
To decode an arbitrary object encoded by the related JSON encoder,
38
+
you should subclass this decoder and define one decode_X method for
39
+
each type of object you want to be able to decode.
40
+
The method name should start with "decode_" and end with the type name.
41
+
The method accepts a Python dictionary with string keys and should be able
42
+
to reconstruct the arbitrary object from the data provided in the dictionary.
43
+
"""
44
+
20
45
def __init__(self, **kwargs):
21
-
kwargs["object_hook"] = self.object_hook
46
+
kwargs["object_hook"] = self._object_hook
22
47
super().__init__(**kwargs)
23
48
24
-
def object_hook(self, obj):
49
+
def _object_hook(self, obj):
50
+
"""Default object hook that matches the encoder behaviour."""
51
+
25
52
try:
26
53
name = obj["__extended_json_type__"]
27
54
decoder = getattr(self, f"decode_{name}")
You can’t perform that action at this time.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4