Reputation: 9253
I had this working fine, but then when there is a date, I had to write a function to serialize it to work with JSON
, however when I read it back from the JSON
, it seems to come in as unicode, not a dictionary.
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
Error:
AttributeError: 'unicode' object has no attribute 'iteritems'
Upvotes: 0
Views: 77
Reputation: 143097
You need only one dump
d = OrderedDict([(1, {'test': datetime.datetime(2016, 2, 1, 20, 21, 27)}), (2, 20)])
with open("my_file.json","w") as f:
json.dump(d, f, default=date_handler)
Upvotes: 1