The following works for IPython 3, but not IPython 4.
The IPython API has functions for reading and writing notebook files. You should use this API and not create JSON directly. For example, the following code snippet converts a script test.py
into a notebook test.ipynb
.
import IPython.nbformat.current as nbf
nb = nbf.read(open('test.py', 'r'), 'py')
nbf.write(nb, open('test.ipynb', 'w'), 'ipynb')
Regarding the format of the .py file understood by nbf.read it is best to simply look into the parser class IPython.nbformat.v3.nbpy.PyReader. The code can be found here (it is not very large):
https://github.com/ipython/ipython/blob/master/jupyter_nbformat/v3/nbpy.py
Edit: This answer was originally written for IPyhton 3. I don't know how to do this properly with IPython 4. Here is an updated version of the link above, pointing to the version of nbpy.py
from the IPython 3.2.1 release:
https://github.com/ipython/ipython/blob/rel-3.2.1/IPython/nbformat/v3/nbpy.py
Basically you use special comments such as # <codecell>
or # <markdowncell>
to separate the individual cells. Look at the line.startswith
statements in PyReader.to_notebook
for a complete list.