我原来的字典是
A = {
'date': datetime.date(2013, 1, 1),
'price': 100
}
由于datetime.date
不可序列化,我添加了一个默认函数来处理:
B = json.dumps(A, default=lambda obj:obj.isoformat() if hasattr(obj, 'isoformat') else obj)
我的问题是,当我使用'date'
将其转换回原始字典时,如何对json.loads
字段进行反序列化?
答案 0 :(得分:9)
from datetime import datetime
def load_with_datetime(pairs, format='%Y-%m-%d'):
"""Load with dates"""
d = {}
for k, v in pairs:
if isinstance(v, basestring):
try:
d[k] = datetime.strptime(v, format).date()
except ValueError:
d[k] = v
else:
d[k] = v
return d
dump = json.dumps(A, default = f)
json.loads(dump, object_pairs_hook=load_with_datetime)
# {u'date': datetime.date(2013, 1, 1), u'price': 100}
答案 1 :(得分:2)
继续您的示例代码,
C = json.loads(B)
C['date'] = datetime.datetime.strptime(C['date'], '%Y-%m-%d')
print C
# {u'date': datetime.datetime(2013, 1, 1, 0, 0), u'price': 100}
答案 2 :(得分:1)
使用pickle模块
import pickle
fileop = open("timeformat.txt","wb")
pickle.dump(A,fileop)
fileop.close()
print pickle.load(open("timeformat.txt","rb"))
print A['Date']
>>>{'date': datetime.date(2013, 1, 1), 'price': 100}
>>>2013-01-01