Jupyter Notebook Format

raw JSON →
5.10.4 verified Tue May 12 auth: no python install: verified quickstart: verified

nbformat is the reference implementation of the Jupyter Notebook format, providing Python APIs for programmatically creating, reading, modifying, and validating Jupyter Notebook files (.ipynb). It is currently at version 5.10.4 and follows the Jupyter project's release cadence, with major versions aligning with significant changes to the notebook format specification.

pip install nbformat
error ModuleNotFoundError: No module named 'nbformat'
cause The `nbformat` package is not installed in the currently active Python environment, or the environment where it is installed is not the one being used by the application (e.g., VS Code, Jupyter).
fix
Ensure nbformat is installed in the correct environment by running: pip install nbformat or conda install nbformat. If using an IDE like VS Code, verify the selected Python interpreter matches the environment where nbformat was installed.
error ValueError: Mime type rendering requires nbformat>=4.2.0 but it is not installed
cause This error typically occurs when a library (e.g., Plotly) attempts to render rich output in a Jupyter Notebook, but the installed version of `nbformat` is older than the required minimum version (e.g., 4.2.0) or is not correctly detected.
fix
Upgrade nbformat to the latest version: pip install --upgrade nbformat. After upgrading, it is often necessary to restart the kernel or the entire Jupyter/VS Code session.
error MissingIDFieldWarning: Code cell is missing an id field, this will become a hard error in future nbformat versions.
cause This warning indicates that one or more cells in a Jupyter notebook are missing a unique 'id' field, which became mandatory in `nbformat` 4.5. This often happens with older notebooks, or when cells are copied and pasted, leading to an incomplete notebook structure.
fix
Use the nbformat.validator.normalize() function to add missing ID fields and normalize the notebook structure. For example: import nbformat; from nbformat import validator; with open('problematic.ipynb', 'r') as f: nb_corrupted = nbformat.read(f, as_version=4); nb_fixed = validator.normalize(nb_corrupted); with open('fixed.ipynb', 'w') as f_out: nbformat.write(nb_fixed, f_out). Newer versions of nbformat (>=5.1.4) provide this normalize method.
error nbformat.ValidationError: ('Notebook failed to convert.',) or NBFormatError
cause A `ValidationError` (or `NBFormatError` in older versions) indicates that the notebook file does not conform to the expected Jupyter Notebook format specification, meaning its JSON structure is invalid. This can be due to file corruption, manual edits that introduce errors, or attempting to read/write a notebook with an incompatible `nbformat` version or schema.
fix
Ensure the notebook file is well-formed JSON. If the issue is due to a version mismatch, explicitly specify the as_version parameter when reading (nbformat.read(fp, as_version=4)), or ensure the notebook's internal nbformat and nbformat_minor metadata fields correctly reflect its structure. For deep corruption, manual inspection and correction of the .ipynb file as plain text might be necessary, or attempting to convert it with a compatible nbconvert version.
breaking nbformat 5.0.0 dropped support for Python 2.x. It now requires Python 3.5+ (currently >= 3.8). If you are on an older Python 3 version, check the specific `nbformat` 5.x patch release for minimum Python requirements.
fix Upgrade your Python environment to Python 3.8 or newer.
deprecated The `nbformat.current` module is deprecated. It was intended for backward compatibility but can lead to confusion regarding notebook versions.
fix Directly import from specific version modules like `nbformat.v4` (e.g., `from nbformat.v4 import new_notebook`) for programmatic notebook creation and manipulation, and use `nbformat.read()` or `nbformat.write()` for file I/O.
gotcha The `validate()` function in nbformat 5.5.0 and later no longer attempts to fix notebook errors during validation. It will now raise a `ValidationError` for invalid notebooks rather than silently modifying them.
fix Ensure your notebooks strictly conform to the expected schema *before* calling `validate()`. If you need to upgrade older notebooks, use `nbformat.convert(nb_node, to_version=4)` explicitly, or rely on `nbformat.read(..., as_version=4)` which performs conversion if needed.
gotcha When reading or writing notebooks, `nbformat.NO_CONVERT` can be passed to the `as_version` or `version` parameters to prevent any version conversion. If you omit `version` during writing, the notebook's own version will be used without conversion.
fix Be explicit about desired notebook format versions. If you want to ensure a specific output format, always set `version=4` (or another target version) in `nbformat.write()`. Similarly, when reading, use `as_version=4` if you want the returned object to be converted to that version.
python os / libc status wheel install import disk
3.10 alpine (musl) - - 0.44s 23.6M
3.10 slim (glibc) - - 0.29s 24M
3.11 alpine (musl) - - 0.64s 26.2M
3.11 slim (glibc) - - 0.61s 26M
3.12 alpine (musl) - - 0.60s 17.9M
3.12 slim (glibc) - - 0.56s 18M
3.13 alpine (musl) - - 0.41s 17.1M
3.13 slim (glibc) - - 0.36s 17M
3.9 alpine (musl) - - 0.50s 23.1M
3.9 slim (glibc) - - 0.52s 23M

This quickstart demonstrates how to create a new Jupyter Notebook programmatically, add markdown and code cells, save it to a `.ipynb` file, and then read the content of an existing notebook. It uses the `nbformat.v4` module for creating notebook components, ensuring compatibility with the current Jupyter Notebook format specification version 4.

import nbformat
from nbformat.v4 import new_notebook, new_markdown_cell, new_code_cell
import os

# 1. Create a new notebook
nb = new_notebook()

# Add a markdown cell
nb.cells.append(new_markdown_cell("## My First Notebook (nbformat)"))

# Add a code cell
code_cell_content = "print('Hello from nbformat!')\nx = 1 + 2\nprint(f'The sum is: {x}')"
nb.cells.append(new_code_cell(code_cell_content))

# Define output path
notebook_filename = 'example_notebook.ipynb'

# 2. Write the notebook to a file
with open(notebook_filename, 'w', encoding='utf-8') as f:
    nbformat.write(nb, f)
print(f"Notebook '{notebook_filename}' created successfully.")

# 3. Read an existing notebook
read_nb = None
if os.path.exists(notebook_filename):
    with open(notebook_filename, 'r', encoding='utf-8') as f:
        # Specify as_version=4 to ensure it's read as the V4 format
        read_nb = nbformat.read(f, as_version=4)
    print(f"\nNotebook '{notebook_filename}' read successfully.")
    print(f"Notebook format version: {read_nb.nbformat}.{read_nb.nbformat_minor}")
    for i, cell in enumerate(read_nb.cells):
        print(f"\n--- Cell {i+1} ({cell.cell_type}) ---")
        print(cell.source)
else:
    print(f"Error: '{notebook_filename}' not found for reading.")