forked from jly8866/archer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extend_json_encoder.py
65 lines (44 loc) · 1.13 KB
/
extend_json_encoder.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
59
60
61
62
63
64
65
# -*- coding: UTF-8 -*-
import simplejson as json
from datetime import datetime, date
from decimal import Decimal
from functools import singledispatch
class MyClass:
def __init__(self, value):
self._value = value
def get_value(self):
return self._value
# 创建非内置类型的实例
mc = MyClass('i am class MyClass ')
dm = Decimal('11.11')
dt = datetime.now()
dat = date.today()
@singledispatch
def convert(o):
raise TypeError('can not convert type')
@convert.register(datetime)
def _(o):
return o.strftime('%Y-%m-%d %H:%M:%S')
@convert.register(date)
def _(o):
return o.strftime('%Y-%m-%d')
# @convert.register(Decimal)
# def _(o):
# return float(o)
@convert.register(MyClass)
def _(o):
return o.get_value()
class ExtendJSONEncoder(json.JSONEncoder):
def default(self, obj):
try:
return convert(obj)
except TypeError:
return super(ExtendJSONEncoder, self).default(obj)
data = {
'mc': mc,
'dm': dm,
'dt': dt,
'dat': dat,
'bigint': 988983860501598208
}
#print(json.dumps(data, cls=ExtendJSONEncoder, bigint_as_string=True))