Pretty JSON Formatting in IPython Notebook

PythonJsonIpython Notebook

Python Problem Overview


Is there an existing way to get json.dumps() output to appear as "pretty" formatted JSON inside ipython notebook?

Python Solutions


Solution 1 - Python

json.dumps has an indent argument, printing the result should be enough:

print(json.dumps(obj, indent=2))

Solution 2 - Python

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:

enter image description here enter image description here

Solution 3 - Python

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

Solution 4 - Python

I am just adding the expanded variable to @Kyle Barron answer:

from IPython.display import JSON
JSON(json_object, expanded=True)

Solution 5 - Python

I found this page looking for a way to eliminate the literal \ns in the output. We're doing a coding interview using Jupyter and I wanted a way to display the result of a function real perty like. My version of Jupyter (4.1.0) doesn't render them as actual line breaks. The solution I produced is (I sort of hope this is not the best way to do it but...)

import json

output = json.dumps(obj, indent=2)

line_list = output.split("\n")  # Sort of line replacing "\n" with a new line

# Now that our obj is a list of strings leverage print's automatic newline
for line in line_list:
    print line

I hope this helps someone!

Solution 6 - Python

For Jupyter notebook, may be is enough to generate the link to open in a new tab (with the JSON viewer of firefox):

from IPython.display import Markdown
def jsonviewer(d):
   f=open('file.json','w')
   json.dump(d,f)
   f.close()
   print('open in firefox new tab:')
   return Markdown('[file.json](./file.json)')

jsonviewer('[{"A":1}]')
'open in firefox new tab:

file.json

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKyle BrandtView Question on Stackoverflow
Solution 1 - PythonfilmorView Answer on Stackoverflow
Solution 2 - PythonKyle BarronView Answer on Stackoverflow
Solution 3 - PythonShankar ARULView Answer on Stackoverflow
Solution 4 - PythonJoe CabezasView Answer on Stackoverflow
Solution 5 - PythonJohn CarrellView Answer on Stackoverflow
Solution 6 - PythonrestrepoView Answer on Stackoverflow