JSON encoding for dict of dicts
You have several options:
Serialize with a custom key prefix that you can pick out and unserialize again:
tuple_key = '__tuple__({})'.format(','.join(key))
would produce
'__tuple__(node1,node2,nodeN)'
as a key, which you could parse back into a tuple on the other side:if key.startswith('__tuple__('): key = tuple(key[10:-1].split(','))
Demo:
>>> key = ('node1', 'node2', 'node3')>>> '__tuple__({})'.format(','.join(key))'__tuple__(node1,node2,node3)'>>> mapped_key = '__tuple__({})'.format(','.join(key))>>> tuple(mapped_key[10:-1].split(','))('node1', 'node2', 'node3')
Don't use dictionaries, use a list of lists:
{'Path': [[[node1, node2 .. nodeN], [float1, float2, float3]], [...]]}
You can build such a list simply from the
dict.items()
result:>>> json.dumps({(1, 2, 3): ('foo', 'bar')}.items())'[[[1, 2, 3], ["foo", "bar"]]]'
and when decoding, feed the whole thing back into
dict()
while mapping each key-value list to tuples:>>> dict(map(tuple, kv) for kv in json.loads('[[[1, 2, 3], ["foo", "bar"]]]')){(1, 2, 3): (u'foo', u'bar')}
The latter approach is more suitable for custom classes as well, as the JSONEncoder.default()
method will still be handed these custom objects for you to serialize back to a suitable dictionary object, which gives means that a suitable object_hook
passed to JSONDecoder()
a chance to return fully deserialized custom objects again for those.