Pretty JSON Formatting in IPython Notebook
Solution 1:
json.dumps
has an indent
argument, printing the result should be enough:
print(json.dumps(obj, indent=2))
Solution 2:
This might be slightly different than what OP was asking for, but you can do use IPython.display.JSON
to interactively view a JSON/dict
object.
from IPython.display import JSON
JSON({'a': [1, 2, 3, 4,], 'b': {'inner1': 'helloworld', 'inner2': 'foobar'}})
Edit: This works in Hydrogen and JupyterLab, but not in Jupyter Notebook or in IPython terminal.
Inside Hydrogen:
Solution 3:
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_data
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)
To ouput your data in collapsible format:
RenderJSON(your_json)
Copy pasted from here: https://www.reddit.com/r/IPython/comments/34t4m7/lpt_print_json_in_collapsible_format_in_ipython/
Github: https://github.com/caldwell/renderjson