I want to use IntEnum in my project and i have to serialize enum value into json and then deserialize it back.
The problem is when i use python 2.7 i get this error:
ValueError: No JSON object could be decoded
When i use python 3.* all is ok.
The code is (for python 2.7):
import json
from enum import IntEnum
class DigitEnum(IntEnum):
A = 1
if __name__ == '__main__':
print DigitEnum.A
a = json.dumps(DigitEnum.A)
print a # DigitEnum.A
a = json.loads(a) # error here
print a
print a == DigitEnum.A
python 3.*:
import json
from enum import IntEnum
class DigitEnum(IntEnum):
A = 1
if __name__ == '__main__':
print(DigitEnum.A)
a = json.dumps(DigitEnum.A)
print(a) # 1
a = json.loads(a)
print(a)
print(a == DigitEnum.A)
Is it possible to avoid creating custom JSONDecoder\JSONEncoder for my enum class or the only way is to use something like this:
a = json.dumps(DigitEnum.A.value)
The primary goal is to save compatibility between to major python versions