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}
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.
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.
enums are not json-serializable in dictionary keys #2278.
dumps() takes in a json object and returns a string.
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"
}
]
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 enum
s as int
s; of course, decoding them will give you an int
back, but that is as good it gets without specifying your encoder/decoder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With