Serialising an Enum member to JSON

后端 未结 7 1874
借酒劲吻你
借酒劲吻你 2020-12-13 11:52

How do I serialise a Python Enum member to JSON, so that I can deserialise the resulting JSON back into a Python object?

For example, this code:

7条回答
  •  粉色の甜心
    2020-12-13 12:31

    The correct answer depends on what you intend to do with the serialized version.

    If you are going to unserialize back into Python, see Zero's answer.

    If your serialized version is going to another language then you probably want to use an IntEnum instead, which is automatically serialized as the corresponding integer:

    from enum import IntEnum
    import json
    
    class Status(IntEnum):
        success = 0
        failure = 1
    
    json.dumps(Status.success)
    

    and this returns:

    '0'
    

提交回复
热议问题