Using fromJSON to create a notebook with default contents in Jupyterlab V4?

Hi! I’m trying to create a jl extension which creates a notebook from JSON contents. I have managed to create, rename and open a notebook with documentManager.newUntitled(), documentManager.rename() and documentManager.openOrReveal().

I have tried this to add default content to created file:

const widget = documentManager.openOrReveal(renamed.path);
widget.context.model.fromJSON(mockContent)

But this doesn’t display anything in the ui, the notebook is opened, but is blank.

Whereas my web search only yielded one post with the below code and although it does display the new content on the Notebook Panel, after closing the notebook and reopening it, its content disappears i.e.: the notebook appears blank/empty.

        const nbPanel: NotebookPanel = await app.commands.execute(
          'notebook:create-new',
          { kernelName: 'python3', activate: true }
        );

        const model = new NotebookModel();
        model.fromJSON(mockContent);

        nbPanel.content.model = model;

Calling nbPanel.content.model.fromJSON is also an option, yet the author of the above code suggests to reassign nbPanel.content.model (which seems to work but then it doesn’t save)

Can someone please help?

1 Like

If anybody comes across this: use the ContentsManager.save() function, which can take an options object, where you can just pass the content.


        const contents = new ContentsManager();
      
        await contents.save(file.path, {
          type: 'notebook',
          content: defaultContent
        });

NB: file is of type Contents.IModel - same as what is being returned by newUntitled or rename functions.

defaultContent is of type any but if you want the correct shape of the object and you don’t know how to get it, just open an .ipynb document with a normal editor in jupyterlab (right click, ‘Open With’, ‘Editor’)

Pro tipp: if you don’t have time to wait for people to answer you, use chatGPT, it will probably point you in the right direction. This is my key take away from this…