首先构建JSON数据结构:
>>> menu = \
... {
... "breakfast":{
... "hours":"7-11",
... "items":{
... "breakfast burritors":"$6.00",
... "pancakes":"$4.00"
... }
... },
... "lunch":{
... "hours":"11-3",
... "items":{
... "hamburger":"$5.00"
... }
... },
... "dinner":{
... "hours":"3-10",
... "items":{
... "spaghetti":"$8.00"
... }
... }
... }
接下来使用dumps()将menu编码为json字符串(menu_json):
>>> import json
>>> menu_json = json.dumps(menu)
>>> menu_json
'{"breakfast": {"items": {"breakfast burritors": "$6.00", "pancakes": "$4.00"}, "hours": "7-11"}, "dinner": {"items": {"spaghetti": "$8.00"}, "hours": "3-10"}, "lunch": {"items": {"hamburger": "$5.00"}, "hours": "11-3"}}'
现在反过来使用loads()把JSON字符串menu_json解析成python的数据结构(menu2):
>>> menu2 = json.loads(menu_json)
>>> menu2
{'breakfast': {'items': {'breakfast burritors': '$6.00', 'pancakes': '$4.00'}, 'hours': '7-11'}, 'dinner': {'items': {'spaghetti': '$8.00'}, 'hours': '3-10'}, 'lunch': {'items': {'hamburger': '$5.00'}, 'hours': '11-3'}}
你可能会在编码或者解析json对象时得到异常,包括对象时间datetime:
上述错误发生是因为标准json没有定义日期或者时间类型,需要自定义处理方式。你可以把datetime转换成json能理解的类型,比如字符串或者epoch值:
>>> now_str = str(now)
>>> json.dumps(now_str)
'"2016-01-31 09:32:10.880944"'
>>> from time import mktime
>>> now_epoch = int(mktime(now.timetuple()))
>>> json.dumps(now_epoch)
'1454261530'
也可以通过继承修改JSON的编码方式,修改datetime编码方式:
>>> class DTEncoder(json.JSONEncoder):
... def default(self,obj):
... if isinstance(obj,datetime.datetime):
... return int(mktime(obj.timetuple()))
... return json.JSONEncoder.default(self,obj)
...
>>> json.dumps(now,cls=DTEncoder)
'1454261530'
新类DTEncoder是JSONEncoder的一个子类。我们需要重载它的default()方法来增加处理datetime的代码。继承确保了剩下的功能与父类的一致性。
函数isinstance()检查obj是否是类datetime.datetime的对象。
>>> type(now)
<class 'datetime.datetime'>
>>> isintance(now,datetime.datetime)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'isintance' is not defined
>>> isinstance(now,datetime.datetime)
True