Creating a new notebook on launch with contents initialized?

Hi there,

I’m new to the community and am having some trouble figuring out how to modify the contents of a notebook programmatically.

Basically I am creating an extension that upon activation, will create a new notebook that will already contain contents (cell data, notebook metadata).

I have a “sample” .ipynb file whose raw contents appear like so:

“cells”: [
“cell_type”: “code”,
“execution_count”: null,
“id”: “f0e5fd3c-73ce-4772-acba-ec62dbbc4a90”,
“metadata”: {},
“outputs”: [],
“source”: [
“print(“hello world”)”
“cell_type”: “raw”,
“id”: “b9d6d461-d25d-4ae1-b806-5f2c0d3c8332”,
“metadata”: {},
“source”: [
“this is normal text”
“metadata”: {
“kernelspec”: {
“display_name”: “Python 3 (ipykernel)”,
“language”: “python”,
“name”: “python3”
“language_info”: {
“codemirror_mode”: {
“name”: “ipython”,
“version”: 3
“file_extension”: “.py”,
“mimetype”: “text/x-python”,
“name”: “python”,
“nbconvert_exporter”: “python”,
“pygments_lexer”: “ipython3”,
“version”: “3.10.4”
“nbformat”: 4,
“nbformat_minor”: 5

And in my extension my activate() function looks like so:

function activate(
app: JupyterFrontEnd,
docManager: IDocumentManager
): void {
// Create a new notebook with Panel
const nbPanel: NotebookPanel = await app.commands.execute(
{ kernelName: ‘python3’, activate: true }

This creates a new Unititled.ipynb file when JupyterLab starts up, however it is empty. I would like to set the contents of the newly created notebook to contain the raw contents of the “sample” notebook. Is there such a way to do that?

Thank you for any help or guidance.

Hi, in case someone stumbles on this- after a lot of digging I finally figured it out.

First, I found this method fromJSON() for INotebookModel which is documented here and used that as a starting point.

I exported my “sample” json as an nbformat.INotebookContent variable.
(The GitHub file here shows how this can be done.)

Then, I created a new Notebook model using the fromJSON() method from the documentation.

const model = new NotebookModel();

Finally, I just set this new model to be the one in my current Notebook Panel (which contained the Untitled.ipynb file) like so:

nbPanel.content.model = model;

And it works! Upon start up, the notebook is opened automatically and default contents are displayed.