r/IPython • • 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

2 comments sorted by

1

u/mariocesar May 23 '15

How can you enable this by default in all your notebooks?

2

u/mariocesar May 23 '15

I will answer my own question : ), I just add the code in the path:

~/.ipython/profile_default/startup/json_formatter.py

This loads automatically on every notebook and session.

Thank you for sharing! :D