2

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?

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.