Examples#

A JSON-like Python dictionary renders the full Python object as text/plain (notice the single quotes).

json_dict = {
    "key1": "value1",
    "key2": {"key21": 42, "key22": True, "key23": None},
    "key3": ["a", "b"],
}
json_dict
{'key1': 'value1',
 'key2': {'key21': 42, 'key22': True, 'key23': None},
 'key3': ['a', 'b']}

It can be wrapped in an output type, which adds the MIME type application/json.

from IPython.display import JSON

JSON(json_dict)

However, there are two issues with this:

  • Now text/plain is <IPython.core.display.JSON object>

  • application/json’s data is the original JSON, and it is left up to renderers how to represent it.

Comparison#

Jupyter Lab renders the following:

Screenshot of json_dict in Jupyter

Whereas MyST-NB renders:

Screenshot of json_dict in HTML by MyST-NB

With myst-nb-json, you will get an interactive rendering that looks similar to Jupyter Lab:

Screenshot of json_dict in HTML with myst-nb-json

MyST-NB-JSON#

from IPython.display import JSON

JSON(json_dict)
  • "root":
    {
    • "key1": "value1",
    • "key2":
      {
      • "key21": 42,
      • "key22": true,
      • "key23": null
      },
    • "key3":
      [
      • "a",
      • "b"
      ]
    }

Expanded#

With the expanded parameter, you can control how much to show by default:

JSON(json_dict, expanded=True)
  • "root":
    {
    • "key1": "value1",
    • "key2":
      {
      • "key21": 42,
      • "key22": true,
      • "key23": null
      },
    • "key3":
      [
      • "a",
      • "b"
      ]
    }

Root#

With the root parameter, you can control the display name:

JSON(json_dict, root="json_dict")
  • "json_dict":
    {
    • "key1": "value1",
    • "key2":
      {
      • "key21": 42,
      • "key22": true,
      • "key23": null
      },
    • "key3":
      [
      • "a",
      • "b"
      ]
    }

Pydantic#

This is also nice for Pydantic models! By default, they are rendered as plain text:

Hide code cell source
from typing import Optional
from pydantic import BaseModel


class Model2(BaseModel):
    key21: int
    key22: bool
    key23: Optional[str]


class ExampleModel(BaseModel):
    key1: str
    key2: Model2
    key3: list[str]
example_model = ExampleModel(**json_dict)
example_model
ExampleModel(key1='value1', key2=Model2(key21=42, key22=True, key23=None), key3=['a', 'b'])
JSON(example_model.model_dump(mode="json"))
  • "root":
    {
    • "key1": "value1",
    • "key2":
      {
      • "key21": 42,
      • "key22": true,
      • "key23": null
      },
    • "key3":
      [
      • "a",
      • "b"
      ]
    }

As a bonus, MyST-NB has been designed that despite the simplified rendering, when you select and copy the text, it will include valid JSON.