2

I want to make my class JSON serializeable and am trying to extend it with the JSONEncoder class. However, why does the default function take the o parameter when it is supposed to be a method of my class.

I want to serialize my class object, not a third object that is passed to the method?

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

def default(self, o):
   try:
       iterable = iter(o)
   except TypeError:
       pass
   else:
       return list(iterable)
   # Let the base class default method raise the TypeError
   return JSONEncoder.default(self, o)
2
  • 1
    You don't extend your class with JSONEncoder, you extend JSONEncoder to handle your class. Commented Sep 1, 2017 at 18:22
  • The class you want to make serializable isn't suppose to inherit from JSONEncoder... that is your fundamental misunderstanding. Commented Sep 1, 2017 at 18:22

1 Answer 1

1

you should do something like this:

>>> import json
>>> class ComplexEncoder(json.JSONEncoder):
...     def default(self, obj):
...         if isinstance(obj, complex):
...             return [obj.real, obj.imag]
...         # Let the base class default method raise the TypeError
...         return json.JSONEncoder.default(self, obj)

maybe you're forgetting json at last return.
take a look at json doc

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.