Personal wiki notebook (not under development)

Json.py 946B

123456789101112131415161718192021222324252627282930313233343536
  1. import warnings
  2. warnings.filterwarnings( "ignore", message = "The sre module is deprecated, please import re." )
  3. from simplejson import JSONEncoder
  4. from datetime import datetime, date
  5. class Json( JSONEncoder ):
  6. def __init__( self, *args, **kwargs ):
  7. JSONEncoder.__init__( self )
  8. if args and kwargs:
  9. raise ValueError( "Please provide either args or kwargs, not both." )
  10. self.__args = args
  11. self.__kwargs = kwargs
  12. def __str__( self ):
  13. if self.__args:
  14. if len( self.__args ) == 1:
  15. return self.encode( self.__args[ 0 ] )
  16. return self.encode( self.__args )
  17. return self.encode( self.__kwargs )
  18. def default( self, obj ):
  19. """
  20. Invoked by JSONEncoder.encode() for types that it doesn't know how to encode.
  21. """
  22. if isinstance( obj, datetime ) or isinstance( obj, date ):
  23. return unicode( obj )
  24. if hasattr( obj, "to_dict" ):
  25. return obj.to_dict()
  26. raise TypeError