() FooBarType , .
, JSON , json, ( ) Enum. , enums34 Ethan Furman ., Python 2.7, "t - Python 3.4.
. , , json.dumps(), . , Python import ed sys.modules, , , , , "" .
, , , . : make_enum_json_serializable.py
""" Module that monkey-patches the json module when it imported so
JSONEncoder.default() automatically checks to see if the object being encoded
is an Enum type and, if so, returns its name.
"""
from enum import Enum
from json import JSONEncoder
_saved_default = JSONEncoder().default
def _new_default(self, obj):
if isinstance(obj, Enum):
return obj.name
else:
return _saved_default
JSONEncoder.default = _new_default
script , , :
from enum import Enum
import json
import make_enum_json_serializable
class FooBarType(Enum):
standard = 0
foo = 1
bar = 2
a_dict = {'name': 'test', 'value': 'test', 'type': FooBarType.foo}
print(json.dumps(a_dict))
:
{"type": "foo", "name": "test", "value": "test"}