user2242044
user2242044

Reputation: 9253

Writing dictionary to JSON then back into Python yields Unicode not dictionary

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

Answers (1)

furas
furas

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

Related Questions