pythonjsonjupyter-notebookipythonjsoniq

How to invoke a cell magic inside a function?


Consider the following program, which I wrote in two Jupyter Notebook cells.

Cell 1:

import rumbledb as rmbl
%load_ext rumbledb
%env RUMBLEDB_SERVER=http://public.rumbledb.org:9090/jsoniq

Cell 2:

%%jsoniq
parse-json("{\"x\":3}}").x

After executing

spark-submit rumbledb-1.21.0-for-spark-3.5.jar serve -p 8001

in a Git Bash console, when I run these two cells in order, the output of the second cell is

Took: 0.2607388496398926 ms
3

How can I encapsulate the second cell in a function, say f, that I can call to thus: f()?

I tried the obvious:

Cell 3:

def f():
    %%jsoniq
    parse-json("{\"x\":3}}").x

Cell 4:

f()

Cell 3 ran successfully, however when I ran cell 4, I got the following error message:

UsageError: Line magic function `%%jsoniq` not found.

I then tried to move the %%jsoniq part to the beginning of the cell, as follows:

Cell 5:

%%jsoniq
def f():
    parse-json("{\"x\":3}}").x

However, running cell 5 yielded the following error message:

Took: 3.5366852283477783 ms
There was an error on line 3 in file:/home/ubuntu/:


Code: [XPST0003]
Message: Parser failed. 

Metadata: file:/home/ubuntu/:LINE:3:COLUMN:0:
This code can also be looked up in the documentation and specifications for more information.

I then tried to follow the advice given in the end of this answer, and ran the following cell:

Cell 6:

from IPython import get_ipython
def f():
    ipython = get_ipython()
    ipython.run_cell_magic('jsoniq', '', 'parse-json("{\"x\":3}}").x')

This executed without problem, but when I then ran cell 4 again (f()), I got the following error message:

Took: 0.5450258255004883 ms
There was an error on line 2 in file:/home/ubuntu/:


Code: [XPST0003]
Message: Parser failed. 

Metadata: file:/home/ubuntu/:LINE:2:COLUMN:0:
This code can also be looked up in the documentation and specifications for more information.

How can I encapsulate cell 2's code in a named function of my own making that I can later invoke in other cells?


Solution

  • Indeed the %jsoniq magic is meant for interactive access.

    However, it should be possible to create a Python function that does what you need if you copy-paste the code behind the %jsoniq magic as indicated here.

    That way the Python function will fully encapsulate the communication with RumbleDB independently of the %jsoniq magic.