Roberto
Roberto

Reputation: 1351

Specializing JSON object encoding with python 3

I'm having some troubles due to the changes to dict.values() and keys() in Python3.

My old code was something like this:

import json
class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, complex):
            return [obj.real, obj.imag]
        return json.JSONEncoder.default(self, obj)

a = { '1' : 2 + 1j, '2' : 4 + 2j }

print(json.dumps(a.values(), cls=ComplexEncoder))

This on Python 3.3+ raise the exception:

TypeError: dict_values([(2+1j), (4+2j)]) is not JSON serializable

The easy workaround is to do list(a.values()), the problem for me is that I have a lot instances like that in the code. Is there a way to extend the ComplexEncoder in order to iterate over the view?

Upvotes: 2

Views: 1142

Answers (1)

Blender
Blender

Reputation: 298532

You could encode the iterable as a list:

class IterEncoder(json.JSONEncoder):
    def default(self, obj):
        try:
            return list(obj)
        except TypeError:
            return super().default(obj)

class ComplexEncoder(IterEncoder):
    def default(self, obj):
        if isinstance(obj, complex):
            return [obj.real, obj.imag]

        return super().default(obj)

Upvotes: 2

Related Questions