_json.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. # Copyright 2009 Canonical Ltd.
  2. # This file is part of lazr.restfulclient.
  3. #
  4. # lazr.restfulclient is free software: you can redistribute it and/or
  5. # modify it under the terms of the GNU Lesser General Public License
  6. # as published by the Free Software Foundation, version 3 of the
  7. # License.
  8. #
  9. # lazr.restfulclient is distributed in the hope that it will be
  10. # useful, but WITHOUT ANY WARRANTY; without even the implied warranty
  11. # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. # Lesser General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Lesser General Public
  15. # License along with lazr.restfulclient. If not, see
  16. # <http://www.gnu.org/licenses/>.
  17. """Classes for working with JSON."""
  18. __metaclass__ = type
  19. __all__ = ["DatetimeJSONEncoder"]
  20. import datetime
  21. from json import JSONEncoder
  22. class DatetimeJSONEncoder(JSONEncoder):
  23. """A JSON encoder that understands datetime objects.
  24. Datetime objects are formatted according to ISO 1601.
  25. """
  26. def default(self, obj):
  27. if isinstance(obj, datetime.datetime):
  28. return obj.isoformat()
  29. return JSONEncoder.default(self, obj)