【发布时间】:2016-05-12 22:10:57
【问题描述】:
我的工作正常,但是当有一个日期时,我必须编写一个函数来序列化它以使用JSON,但是当我从JSON 读回它时,它似乎进来了作为 unicode,而不是字典。
from collections import OrderedDict
import json
import datetime
def date_handler(obj):
return obj.isoformat() if hasattr(obj, 'isoformat') else obj
d = OrderedDict([(1, {'test': datetime.datetime(2016, 2, 1, 20, 21, 27)}), (2, 20)])
d = json.dumps(d, default=date_handler)
with open("my_file.json","w") as f:
json.dump(d,f)
with open('my_file.json') as data_file:
data = json.load(data_file)
print data
print type(data)
for key, value in data.iteritems():
print key, value
错误:
AttributeError: 'unicode' object has no attribute 'iteritems'
【问题讨论】:
-
你
dump两次,所以你的文件中有奇怪的数据。 -
@furas 我认为可能是这种情况,我不太确定
dumps函数在做什么,我应该删除哪个,我该怎么做?
标签: python json python-2.7 dictionary unicode