[Python] python/Jupyter-lab: How to use built-in JSON visualization functionality for a...

Discussão em 'Python' iniciado por Stack, Março 25, 2025.

  1. Stack

    Stack Membro Participativo

    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,

    [​IMG]

    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?

    Continue reading...

Compartilhe esta Página