Skip to content

Commit 07254c0

Browse files
burivuhjbenua
authored andcommitted
fix key dicts for json
1 parent 6322cc0 commit 07254c0

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

snippets/pyaloha/protocol.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,21 @@
33
import inspect
44
import json
55
import multiprocessing
6+
import sys
67
import traceback
78

9+
10+
if sys.version_info[0] == 3:
11+
def decode_keys_for_json(dct):
12+
return {
13+
(k.decode() if isinstance(k, bytes) else k): v
14+
for k, v in dct.items()
15+
}
16+
else:
17+
def decode_keys_for_json(dct):
18+
return dct
19+
20+
821
DAY_FORMAT = '%Y%m%d'
922
UNIQ_DAY_FORMAT = 'dt' + DAY_FORMAT
1023

@@ -143,11 +156,17 @@ def custom_loads(dct):
143156

144157
class CustomEncoder(json.JSONEncoder):
145158
def default(self, obj):
146-
if hasattr(obj, '__dumpdict__'):
147-
return obj.__dumpdict__()
148159
if not isinstance(obj, str) and isinstance(obj, bytes):
149160
# in python 2.7 str is bytes; don't decode it
150161
return obj.decode()
162+
163+
if hasattr(obj, '__dumpdict__'):
164+
obj = obj.__dumpdict__()
165+
166+
if isinstance(obj, dict):
167+
# process json unprocessable dict keys
168+
return decode_keys_for_json(obj)
169+
151170
# Let the base class default method raise the TypeError
152171
return super(CustomEncoder, self).default(obj)
153172

0 commit comments

Comments
 (0)