LoginSignup
5
4

More than 1 year has passed since last update.

Python の列挙型を JSON Serializable にする方法

Posted at

Python の列挙型はそのままでは JSON Serialize することができない。

from enum import Enum

class NUMBERS(Enum):
    ONE = "one"
    TWO = "two"
    THREE = "three"
import json

json.dumps(NUMBERS.ONE)  #=> TypeError: Object of type NUMBERS is not JSON serializable

この場合、JSON Serializable な型のサブクラスにすると解決する。

from enum import Enum

class NUMBERS(str, Enum):
    ONE = "one"
    TWO = "two"
    THREE = "three"
import json

json.dumps(NUMBERS.ONE)  #=> "one"

この例では値が文字列なので str のサブクラスにした。
値が整数の場合は同様に int のサブクラスにしてもよいが、代わりに IntEnum を使うこともできる。

参考

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4