Home > Software design >  Python: converting class objects to JSON - object is not JSON serializable
Python: converting class objects to JSON - object is not JSON serializable

Time:01-12

I have a list of objects in my Python code. Each object is of type Outer with associated Inner objects - the classes are defined like this:

from decimal import Decimal

@dataclass
class Inner:
    col_a: Decimal
    col_b: str
    col_c: List['str']

@dataclass
class Outer:
    col_a: str
    col_b: Decimal
    col_c: List[Inner]

I would like to convert these objects into JSON. As I am using Decimal, I was hoping to just create my own encoder and use it in conjunction with json.dumps():

class DecimalJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return str(obj)
        else:
            return super(DecimalJsonEncoder, self).default(obj)

... and...

my_json = json.dumps(my_list, cls=DecimalJsonEncoder)

However, when I create a list of Outer objects (my_list) and try to create JSON, I get this error:

TypeError: Object of type Outer is not JSON serializable

I'm using Python 3.7.

Thanks in advance for any assistance.

CodePudding user response:

You wish the encoder to support both Decimal and dataclasses. You can do it like so:

import dataclasses, json

class JSONEncoder(json.JSONEncoder):
        def default(self, o):
            if dataclasses.is_dataclass(o):
                return dataclasses.asdict(o)
            if isinstance(obj, Decimal):
                return str(obj)
            return super().default(o)

json.dumps(foo, cls=JSONEncoder)
  •  Tags:  
  • Related