'How to get the raw contents of a Jupyerlab notebook .ipynb file?

Lets say I have a jupyter notebook .ipynb file created, with a cell block of type code and type markdown. If I open the file to see the raw contents, I see something like this

{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f0e5fd3c-73ce-4772-acba-ec62dbbc4a90",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello world\n"
     ]
    }
   ],
   "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
}

How would I go about programmatically getting the raw contents of a current notebook that is being worked on? Is such a thing possible? I've tried looking into the JupyterLab Contents API and IPython but can't seem to find a solution to get the raw contents of the file. Any help or advice is appreciated, thanks!



Solution 1:[1]

There is a button to export it. For example, opening it in vscode, beside the variables in the top right of the screen, there are 3 dots. Click on that > export > Python Script

Solution 2:[2]

Try this:

import codecs

jupyter_file = codecs.open(filePath, 'r')
source_data = jupyter_file.read()

print(source_data)

source_data gives the raw content of .ipynb file as a JSON string. You can use json.loads() to parse that string and use it or dump it in a separate file as you need.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 March_G
Solution 2