JSON#

Open this notebook in Jupyterlite | Download this notebook from GitHub (right-click to download).


import datetime as dt
import json

import panel as pn

pn.extension()

The JSON pane allows rendering arbitrary JSON strings, dicts and other json serializable objects in a panel.

Parameters:#

For details on other options for customizing the component see the layout and styling how-to guides.

  • depth (int, default=1): Depth to which the JSON structure is expanded on initialization (depth=-1 indicates full expansion).

  • encoder (json.JSONEncoder subclass): Custom JSONEncoder class used to serialize objects that are not natively JSON serializable.

  • hover_preview (bool, default=False): Whether to enable hover preview for collapsed nodes.

  • object (str or object): JSON string or JSON serializable object.

  • theme (str): The color theme, one of 'light' or 'dark'. If no value is provided, it defaults to the current theme set by pn.config.theme, as specified in the JSON.THEME_CONFIGURATION dictionary. If not defined there, it falls back to 'light'.


The JSON pane can be used to render a tree view of arbitrary JSON objects which may be defined as a string or a JSON-serializable Python object.

json_obj = {
    'boolean': False,
    'dict': {'a': 1, 'b': 2, 'c': 3},
    'int': 1,
    'float': 3.1,
    'list': [1, 2, 3],
    'null': None,
    'string': 'A string',
}

json_pane = pn.pane.JSON(json_obj, name='JSON')

json_pane

The object may also be a JSON string. Use depth to control how many levels of the tree are expanded initially (-1 expands everything) and theme to switch the color scheme:

nested = json.dumps({'level1': {'level2': {'level3': {'level4': 'deep'}}}, 'items': list(range(5))})

pn.Row(
    pn.pane.JSON(nested, depth=1, name='depth=1'),
    pn.pane.JSON(nested, depth=-1, theme='dark', name='depth=-1, dark'),
)

Objects that are not natively JSON serializable, such as dates, can be rendered by providing a custom encoder:

class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (dt.date, dt.datetime)):
            return obj.isoformat()
        return super().default(obj)

pn.pane.JSON({'created': dt.datetime(2024, 1, 1, 12, 30), 'tags': ['a', 'b']}, encoder=DateEncoder, depth=-1)

Controls#

The JSON pane exposes a number of options which can be changed from both Python and Javascript. Try out the effect of these parameters interactively:

pn.Row(json_pane.controls(jslink=True), json_pane)

Open this notebook in Jupyterlite | Download this notebook from GitHub (right-click to download).