Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to dump an enum in json without passing an encoder to json.dumps()?

My problem could be summarised by 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.

I primarily though of implementing a JsonEncoder and adding it to the json.dumps() call but I cannot change the line where json.dumps() call is made.

So, my question is : Is it possible to dump an enum in json without passing an encoder to json.dumps(), but instead, by adding class method(s) in FooBarType enum ?

I expect to extract the following json:

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

or

{'name': 'test', 'value': 'test', 'type': 1}
like image 471
Axel Borja Avatar asked Apr 18 '16 16:04

Axel Borja


People also ask

What is the difference between JSON dump and JSON dumps?

json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.

What is JSON dumps () method?

The dump() method is used when the Python objects have to be stored in a file. The dumps() is used when the objects are required to be in string format and is used for parsing, printing, etc, . The dump() needs the json file name in which the output has to be stored as an argument.

Are enums JSON serializable?

enums are not json-serializable in dictionary keys #2278.

What does JSON dump return?

dumps() takes in a json object and returns a string.


2 Answers

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))

Result:

[
    {
        "name": "car",
        "color": "red"
    },
    {
        "name": "dog",
        "color": "blue"
    }
]
like image 54
gil9red Avatar answered Oct 20 '22 12:10

gil9red


Sadly, there is no direct support for Enum in JSON.

The closest automatic support is to use IntEnum (which enum34 also supports), and then json will treat your enums as ints; of course, decoding them will give you an int back, but that is as good it gets without specifying your encoder/decoder.

like image 20
Ethan Furman Avatar answered Oct 20 '22 14:10

Ethan Furman