-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCustom_json_encoding_2.py
58 lines (51 loc) · 1.41 KB
/
Custom_json_encoding_2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# Serializing the objects which are not JSON serializable, using singledispatch decorator
import json
from decimal import Decimal
from fractions import Fraction
from functools import singledispatch
from datetime import datetime
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
self.create_dt = datetime.utcnow()
def __repr__(self):
return f'Person(name={self.name}, age={self.age})'
def toJSON(self):
return vars(self)
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def __repr__(self):
return f'Point(x={self.x}, y={self.y})'
@singledispatch
def json_format(arg):
print(arg)
try:
print('\ttrying to use toJSON()...')
return arg.toJSON()
except AttributeError:
print('\tFailed - trying to use vars...')
try:
return vars(arg)
except TypeError:
print('\tFailed - using string repr...')
return str(arg)
@json_format.register(datetime)
def _(arg):
return arg.isoformat()
@json_format.register(set)
def _(arg):
return list(arg)
@json_format.register(Decimal)
def _(arg):
return f'Decimal({str(arg)})'
d= dict(a=1+1j,
b=Decimal('0.5'),
c= Fraction(1,3),
p = Person('python', 23),
pt = Point(0,0),
time = datetime.utcnow()
)
print(json.dumps(d, default=json_format))