forked from zhanghe06/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_dumps.py
More file actions
73 lines (63 loc) · 1.38 KB
/
test_dumps.py
File metadata and controls
73 lines (63 loc) · 1.38 KB
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
66
67
68
69
70
71
72
73
#!/usr/bin/env python
# encoding: utf-8
"""
@author: zhanghe
@software: PyCharm
@file: test_dumps.py
@time: 16-4-11 下午8:57
"""
import json
from datetime import date, datetime
from decimal import Decimal
def __default(obj):
"""
支持 datetime Decimal 的 json encode
TypeError: datetime.datetime(2015, 10, 21, 8, 42, 54) is not JSON serializable
:param obj:
:return:
"""
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
elif isinstance(obj, Decimal):
return str(obj)
else:
raise TypeError('%r is not JSON serializable' % obj)
row = {
'db': {
'host': '127.0.0.1',
'port': 3306
},
'proxy': [
'http://127.0.0.1:1080',
'https://127.0.0.1:1080'
],
'test_none': None,
'test_bool': True,
'time': datetime.now(),
'price': Decimal('12.68'),
'time_list': [
datetime.now()
]
}
print json.dumps(row, indent=4, ensure_ascii=False, default=__default)
"""
{
"time_list": [
"2016-07-09 23:02:12"
],
"price": "12.68",
"db": {
"host": "127.0.0.1",
"port": 3306
},
"test_bool": true,
"test_none": null,
"proxy": [
"http://127.0.0.1:1080",
"https://127.0.0.1:1080"
],
"time": "2016-07-09 23:02:12"
}
"""