Search code examples
pythonjsonmarkdownjupyter-notebookcarriage-return

Include carriage return correctly in iPython notebooks when writing using json.dump


I'm trying to generate iPython notebooks as json files with Python. I'm not sure how to write carriage returns to file in cells that I've specified as cell_type markdown. I've tried double spaces, as suggested here, and I can get the markdown to make a new line by specifying <br /> but if I include a header specification to the markdown it treats the whole input as a header.

For instance:

import json

# Single markdown cell as a dictionary
cell = {
  "cell_type" : "markdown",
  "metadata" : {'collapsed': False, 'name': 'test'},
  "source" : ["## Header line",
    "<br />", 
    "Second line, not a header...hopefully"],
}

# Create ipython notebook dictionary
nbdict = { 'metadata': {}, \
    'nbformat': 4,
    'nbformat_minor': 0,
    'cells': [cell]
    }

with open('test.ipynb', 'w') as outfile:
    json.dump(nbdict, outfile)

Then if I open this with ipython notebook test.ipynb I have the following output:

Header line Second line, not a header...hopefully

But it's all in bold type, so the whole input is being treated as a one line header.

How do I specify carriage returns properly, so that headers are honoured for just a single line, when I'm creating these notebooks?


Solution

  • Markdown uses newlines to separate lines, not HTML <br/> tags. Include newlines in your source lines; use double newlines to separate paragraph elements (including headers):

    cell = {
        "cell_type": "markdown",
        "metadata": {'collapsed': False, 'name': 'test'},
        "source": [
            "## Header line\n\n",
            "Second line, not a header...hopefully"
        ],
    }