6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have 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 を使うこともできる。

参考

6
5
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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?