0

IPython/Jupyter has built-in functionality to visualise JSON structures as an interactive tree where you can expand and collapse nodes. I like using it for lists and dictionaries, but now I want to use it for visualising the content of dataclasses also:

import IPython
from dataclasses import dataclass
import dataclasses

@dataclass
class TestDC:
    id: str
    val: int

_ipy = IPython.get_ipython()
_json_formatter = _ipy.display_formatter.formatters["application/json"]
_json_formatter.for_type(dict, lambda obj: obj)
_json_formatter.for_type(list, lambda obj: obj)
_json_formatter.for_type(TestDC, lambda obj: dataclasses.asdict(obj))

dc1 = TestDC('a', 1)
dc2 = TestDC('b', 2)

In Jupyter-lab, this works fine when visualising the content of a single TestDC object,

enter image description here

but when I try to visualise the content of a list of TestDC objects, like [dc1, dc2], an error occurs: ValueError: Can't clean for JSON: TestDC(id='a', val=1).

I understand that there's no automatic JSON serialisation of dataclasses, but I don't understand why the built-in visualisation functionality is able to process/visualise the content of a single TestDC object and also nested list and dictionary objects, but runs into troubles when processing a list of objects, for which it knows how to visualise them individually...

What am I missing here?

0

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.