This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author barry
Recipients barry, eli.bendersky, ethan.furman, ncoghlan, pitrou
Date 2013-06-19.13:54:54
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <20130619095449.7c7ef695@anarchist>
In-reply-to <>
On Jun 19, 2013, at 01:48 PM, Nick Coghlan wrote:

>I created issue 18264 after I tried it and found my theoretical concern
>wasn't theoretical at all: swapping a true integer for the current
>incarnation of enum.IntEnum breaks (at least) JSON serialisation, which means
>we can't use it in its current form to replace stdlib constants.

JSON has to be taught how to serialize enums.  Of course, it also has to be
taught how to serialize datetimes, timedeltas, and other common data types.

In Mailman, I use the following subclass of json.JSONEncoder.  Note though
that in my REST API, I always know the class/enum that a string should be
associated with so my deserializer always does the right thing.

class ExtendedEncoder(json.JSONEncoder):
    """An extended JSON encoder which knows about other data types."""

    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        elif isinstance(obj, timedelta):
            # as_timedelta() does not recognize microseconds, so convert these
            # to floating seconds, but only if there are any seconds.
            if obj.seconds > 0 or obj.microseconds > 0:
                seconds = obj.seconds + obj.microseconds / 1000000.0
                return '{0}d{1}s'.format(obj.days, seconds)
            return '{0}d'.format(obj.days)
        elif isinstance(obj, Enum):
            # It's up to the decoding validator to associate this name with
            # the right Enum class.
        return json.JSONEncoder.default(self, obj)
Date User Action Args
2013-06-19 13:54:54barrysetrecipients: + barry, ncoghlan, pitrou, eli.bendersky, ethan.furman
2013-06-19 13:54:54barrylinkissue17961 messages
2013-06-19 13:54:54barrycreate