Nikita Ryanov
Nikita Ryanov

Reputation: 1570

Python 2.7 IntEnum: No JSON object could be decoded

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

Upvotes: 1

Views: 303

Answers (1)

Ethan Furman
Ethan Furman

Reputation: 69110

In Python 3.5+ json was modified to work properly with IntEnum so that, for example:

json.dumps(DigitEnum.A) == 1

This change was not backported to 2.7 (and won't be) so the corresponding code in 2.7 results in:

json.dumps(DigitEnum.A) == 'DigitEnum.A'

which is a str, not a DigitEnum and not an int.


Side note: always use repr() when debugging so you can see what the actual types/values are.

Upvotes: 2

Related Questions