[b]"How to handle embedded objects with Python json.dumps? Struggling with serialization!"[/b] or [b]"Python json.

14 Replies, 1453 Views

Pro tip: `json.JSONEncoder` subclassing!

Override the `default` method to handle your custom objects properly. Way cleaner than hacking it with `default=str`.

```python
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, YourCustomClass):
return obj.__dict__
return super().default(obj)

json.dumps(your_data, cls=CustomEncoder)
```

Messages In This Thread



Users browsing this thread: 1 Guest(s)