def asjson(obj, seen=None):
if isinstance(obj, collections.Mapping) or isiter(obj):
# prevent traversal of recursive structures
if seen is None:
seen = set()
elif id(obj) in seen:
return '__RECURSIVE__'
seen.add(id(obj))
if hasattr(obj, '__json__') and type(obj) is not type:
return obj.__json__()
elif isinstance(obj, collections.Mapping):
result = collections.OrderedDict()
for k, v in obj.items():
try:
result[asjson(k, seen)] = asjson(v, seen)
except TypeError:
debug('Unhashable key?', type(k), str(k))
raise
return result
elif isiter(obj):
return [asjson(e, seen) for e in obj]
else:
return obj
评论列表
文章目录