Serialising an Enum member to JSON

后端 未结 7 1916
借酒劲吻你
借酒劲吻你 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:11

    I know this is old but I feel this will help people. I just went through this exact problem and discovered if you're using string enums, declaring your enums as a subclass of str works well for almost all situations:

    import json
    from enum import Enum
    
    class LogLevel(str, Enum):
        DEBUG = 'DEBUG'
        INFO = 'INFO'
    
    print(LogLevel.DEBUG)
    print(json.dumps(LogLevel.DEBUG))
    print(json.loads('"DEBUG"'))
    print(LogLevel('DEBUG'))
    

    Will output:

    LogLevel.DEBUG
    "DEBUG"
    DEBUG
    LogLevel.DEBUG
    

    As you can see, loading the JSON outputs the string DEBUG but it is easily castable back into a LogLevel object. A good option if you don't want to create a custom JSONEncoder.

提交回复
热议问题