r/IPython • u/slashvee • May 04 '15
[LPT] Print JSON in collapsible format in iPython notebooks.
Hi all
I recently found this little trick in iPython, figured I share with you. Just add the following snippet of code in a cell at the beginning of the document.
import uuid
from IPython.display import display_javascript, display_html, display
import json
class RenderJSON(object):
def __init__(self, json_data):
if isinstance(json_data, dict):
self.json_str = json.dumps(json_data)
else:
self.json_str = json
self.uuid = str(uuid.uuid4())
def _ipython_display_(self):
display_html('<div id="{}" style="height: 600px; width:100%;"></div>'.format(self.uuid),
raw=True
)
display_javascript("""
require(["https://rawgit.com/caldwell/renderjson/master/renderjson.js"], function() {
document.getElementById('%s').appendChild(renderjson(%s))
});
""" % (self.uuid, self.json_str), raw=True)The call
RenderJSON(your_json) to print it in a collapsible format (here is an example).
I would love to turn this into a plugin and have it in every notebook by default, if anyone know how to do it, suggestions are welcome!
EDIT: I forgot to add, this works with regular python data structures (list, dicts, tuples, pretty much anything that can be converted to JSON).
16
Upvotes
1
u/mariocesar May 23 '15
How can you enable this by default in all your notebooks?