How to display Python objects with nested data structure nicely?

Hi,
I run Jupyter notebooks inside VS Code. I need some help on displaying objects with nested data structure so that I can inspect their contents. The following is an example. Thanks.

In case I want better readability I take this route:

import json

json.loads(ai_msg.model_dump_json())
3 Likes

That works very well.Thank you!

1 Like

Hi,
I am relatively new to python. Please do not mind if the query is basic. Is there a reason why you assumed model_dump_json() works here?

@Basic_queries:

Good question.

In the screenshot the model used is gpt-4o-2024-08-06 so my first assumption is this AIMessage Object is conform to the standard defined for messages in the openai python module (it was a good guess). You could now start looking through documentation for available methods/functions. But what I like to do: you create such a message object (by using the openai api with openai module or any other openai conform endpoint/module) and try to work with it. In this case (inside a notebook opened in jupyterlab with default python kernel and openai module installed and key in environment variable):

import openai

response = openai.chat.completions.create(
    model="gpt-5.2",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Who won the world series in 2020?"},
        {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
        {"role": "user", "content": "Where was it played?"}
    ]
)

You run this and in the next cell you just type response. and hit tab. You get the autocompletion list with available functions for the response object. Today i would use response.dict() this way you could skip the whole json shenanigans.

2 Likes

Oh, that’s intelligent of you to do it. Great explanation, thank you!