import datetime
import json
def json_debug_handler(obj):
if not hasattr(obj, 'originalObject'):
return None
obj = obj.originalObject
print("object received:")
print type(obj)
print("\n\n")
if isinstance(obj, datetime.datetime):
return obj.isoformat()
elif isinstance(obj,mDict):
return {'orig':obj, 'attrs': vars(obj)}
elif isinstance(obj,mList):
return {'orig':obj, 'attrs': vars(obj)}
else:
return obj
def debug(obj):
class Debug:
def __init__(self,obj):
self.originalObject = obj
if obj.__class__ == list:
return [debug(item) for item in obj]
elif obj.__class__ == tuple:
return (debug(item) for item in obj)
elif obj.__class__ == dict:
return dict((key,debug(obj[key])) for key in obj)
else:
return Debug(obj)
class mDict(dict):
pass
class mList(list):
pass
def test_debug_json():
games = mList(['mario','contra','tetris'])
games.src = 'console'
scores = mDict({'dp':10,'pk':45})
scores.processed = "qunprocessed"
test_json = { 'games' : games , 'scores' : scores , 'date': datetime.datetime.now() }
test_json = debug(test_json)
print(json.dumps(test_json,default=json_debug_handler))
if __name__ == '__main__':
test_debug_json()
aW1wb3J0IGRhdGV0aW1lCmltcG9ydCBqc29uCgpkZWYganNvbl9kZWJ1Z19oYW5kbGVyKG9iaik6CiAgICBpZiBub3QgaGFzYXR0cihvYmosICdvcmlnaW5hbE9iamVjdCcpOgogICAgICAgIHJldHVybiBOb25lCiAgICBvYmogPSBvYmoub3JpZ2luYWxPYmplY3QKICAgIHByaW50KCJvYmplY3QgcmVjZWl2ZWQ6IikKICAgIHByaW50IHR5cGUob2JqKQogICAgcHJpbnQoIlxuXG4iKQogICAgaWYgIGlzaW5zdGFuY2Uob2JqLCBkYXRldGltZS5kYXRldGltZSk6CiAgICAgICAgcmV0dXJuIG9iai5pc29mb3JtYXQoKQogICAgZWxpZiBpc2luc3RhbmNlKG9iaixtRGljdCk6CiAgICAgICAgcmV0dXJuIHsnb3JpZyc6b2JqLCAnYXR0cnMnOiB2YXJzKG9iail9CiAgICBlbGlmIGlzaW5zdGFuY2Uob2JqLG1MaXN0KToKICAgICAgICByZXR1cm4geydvcmlnJzp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qc29uX2RlYnVnX2hhbmRsZXIpKQogCmlmIF9fbmFtZV9fID09ICdfX21haW5fXyc6CiAgICB0ZXN0X2RlYnVnX2pzb24oKQo=
object received:
<type 'datetime.datetime'>
object received:
<class '__main__.mList'>
object received:
<class '__main__.mDict'>
{"date": "2013-07-22T23:35:15.202687", "games": {"attrs": {"src": "console"}, "orig": ["mario", "contra", "tetris"]}, "scores": {"attrs": {"processed": "qunprocessed"}, "orig": {"pk": 45, "dp": 10}}}