Is it possible to unload enum in json without passing the encoder to json.dumps ()?

My problem can be reduced to the following example:

from enum import Enum
import json

class FooBarType(Enum):
    standard = 0
    foo = 1
    bar = 2

dict = {'name': 'test', 'value': 'test', 'type': FooBarType.foo}

json.dumps(dict)

TypeError: <FooBarType.foo: 1> is not JSON serializable

I get a type error because enums are not JSON serializable.

First of all, I implement JsonEncoderand add it to the call json.dumps(), but I cannot change the line in which the call is made json.dumps().

So my question is: Is it possible to reset enum to json without passing the encoder to json.dumps(), but instead by adding a class (s) method to FooBarTypeenum?

I expect to extract the following json:

{'name': 'test', 'value': 'test', 'type': 'foo'}

or

{'name': 'test', 'value': 'test', 'type': 1}
+4
source share
4 answers

, , Enum.

: Enum:

class FooBarType:
    standard = 0
    foo = 1
    bar = 2

dict = {'type': FooBarType.foo}
json.dumps(dict)

:

class EnumIntValue(int):
    def __new__(cls, name, value):
        c = int.__new__(cls, int(value))
        c.name = name
        return c
    def __repr__(self):
        return self.name
    def __str__(self):
        return self.name

class FooBarType:
    standard = EnumIntValue('standard',0)
    foo = EnumIntValue('foo',0)
    bar = EnumIntValue('bar',2)

dict = {'type': FooBarType.foo}
json.dumps(dict)

{"type": foo}

json, .

+3

, Enum JSON .

IntEnum ( enum34 ), json Enum int s; , int , , /.

+3

() 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  # Save default method.

def _new_default(self, obj):
    if isinstance(obj, Enum):
        return obj.name  # could also be obj.value
    else:
        return _saved_default

JSONEncoder.default = _new_default # Set new default method.

script , , :

from enum import Enum
import json
import make_enum_json_serializable  # ADDED

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"}
+2

Try:

from enum import Enum

# class StrEnum(str, Enum):
#     """Enum where members are also (and must be) strs"""

class Color(str, Enum):
    RED = 'red'
    GREEN = 'green'
    BLUE = 'blue'


data = [
    {
        'name': 'car',
        'color': Color.RED,
    },
    {
        'name': 'dog',
        'color': Color.BLUE,
    },
]

import json
print(json.dumps(data))

:

[
    {
        "name": "car",
        "color": "red"
    },
    {
        "name": "dog",
        "color": "blue"
    }
]
+2

All Articles