fork download
  1. import datetime
  2. import json
  3.  
  4. def json_debug_handler(obj):
  5. if not hasattr(obj, 'originalObject'):
  6. return None
  7. obj = obj.originalObject
  8. print("object received:")
  9. print type(obj)
  10. print("\n\n")
  11. if isinstance(obj, datetime.datetime):
  12. return obj.isoformat()
  13. elif isinstance(obj,mDict):
  14. return {'orig':obj, 'attrs': vars(obj)}
  15. elif isinstance(obj,mList):
  16. return {'orig':obj, 'attrs': vars(obj)}
  17. else:
  18. return obj
  19.  
  20.  
  21. def debug(obj):
  22. class Debug:
  23. def __init__(self,obj):
  24. self.originalObject = obj
  25. if obj.__class__ == list:
  26. return [debug(item) for item in obj]
  27. elif obj.__class__ == tuple:
  28. return (debug(item) for item in obj)
  29. elif obj.__class__ == dict:
  30. return dict((key,debug(obj[key])) for key in obj)
  31. else:
  32. return Debug(obj)
  33.  
  34.  
  35. class mDict(dict):
  36. pass
  37.  
  38.  
  39. class mList(list):
  40. pass
  41.  
  42.  
  43. def test_debug_json():
  44. games = mList(['mario','contra','tetris'])
  45. games.src = 'console'
  46. scores = mDict({'dp':10,'pk':45})
  47. scores.processed = "qunprocessed"
  48. test_json = { 'games' : games , 'scores' : scores , 'date': datetime.datetime.now() }
  49. test_json = debug(test_json)
  50. print(json.dumps(test_json,default=json_debug_handler))
  51.  
  52. if __name__ == '__main__':
  53. test_debug_json()
  54.  
Success #stdin #stdout 0.1s 8976KB
stdin
Standard input is empty
stdout
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}}}