I have a nested Python data structure with datetime.datetime objects and namedtuples along the following lines:
from datetime import datetime as dt
from datetime import timedelta
from collections import namedtuple
nt = namedtuple('n', 'name, contact')
f1 = nt('jules', '1234')
f2 = nt('dan', '5678')
x = [
[dt.now() + timedelta(minutes=1), f1],
[dt.now() + timedelta(hours=1), f2],
]
and an Encoder something like this:
import json
class TestEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
return json.JSONEncoder.default(self, obj)
print json.dumps(x, cls=TestEncoder) outputs:
[["2012-06-21T00:48:03.296381", ["jules", "1234"]],
["2012-06-21T01:47:03.296423", ["dan", "5678"]]]
I’d like to turn the namedtuples into dicts (presumably using the namedtuple ._asdict() method), to get the following output:
[["2012-06-21T00:48:03.296381", {"name":"jules", "contact":"1234"}],
["2012-06-21T01:47:03.296423", {"name":"dan", "contact":"5678"}]]
How can I preserve the general data structure, but json dump the namedtuples as dicts?
After re-reading the docs, this appears to be impossible using the built in
jsonlib as the only override mechanism (default) only gets called after known types (including tuples)simplejsonmakes this trivial by giving you anamedtuple_as_objectflag tosimplejson.dump