Skip to content

Instantly share code, notes, and snippets.

@t27
Last active February 5, 2024 18:40
Show Gist options
  • Save t27/48b3ac73a1479914f9fe9383e5d45325 to your computer and use it in GitHub Desktop.
Save t27/48b3ac73a1479914f9fe9383e5d45325 to your computer and use it in GitHub Desktop.
Render JSON as a collapsible field in jupyter notebooks - Updated - Also includes instructions for interleaving with print statements
## Add this to the first block in your note book
import uuid
from IPython.core.display import display, HTML
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())
# This line is missed out in most of the versions of this script across the web, it is essential for this to work interleaved with print statements
self._ipython_display_()
def _ipython_display_(self):
display(HTML('<div id="{}" style="height: auto; width:100%;"></div>'.format(self.uuid)))
display(HTML("""<script>
require(["https://rawgit.com/caldwell/renderjson/master/renderjson.js"], function() {
renderjson.set_show_to_level(1)
document.getElementById('%s').appendChild(renderjson(%s))
});</script>
""" % (self.uuid, self.json_str)))
# Since this is copy-pasted wrongly(mostly) at a lot of places across the web, i'm putting the fixed, updated version here, mainly for self-reference
## To use this function, call this, this now works even when you have a print statement before or after the RenderJSON call
RenderJSON(dict_to_render)
@melgor
Copy link

melgor commented Jul 18, 2019

Thanks for script!
I have problem that it reders me two instances of JSON in Jupyter, look like that:
Screenshot 2019-07-18 at 09 23 51

Any thoughts why?

@john012343210
Copy link

Thanks for script!
I have problem that it reders me two instances of JSON in Jupyter, look like that:
Screenshot 2019-07-18 at 09 23 51

Any thoughts why?

same problem . hahahaha, i don't know why too

@ljmartin
Copy link

ljmartin commented Sep 4, 2020

Comment out the line self._ipython_display_() and you'll get one copy

@2Dews
Copy link

2Dews commented Oct 4, 2021

Came here from. I had some errors with datatime objects in my json, "TypeError: Object of type datetime is not JSON serializable". This was my fix for that problem thanks to.

`import uuid
from IPython.core.display import display, HTML, JSON
import json
import datetime
class DateTimeEncoder(json.JSONEncoder):
def default(self, z):
if isinstance(z, datetime.datetime):
return (str(z))
else:
return super().default(z)

class RenderJSON(object):
def init(self, json_data):
if isinstance(json_data, dict):
self.json_str = json.dumps(json_data,cls=DateTimeEncoder)
else:
self.json_str = json_data
self.uuid = str(uuid.uuid4())
# This line is missed out in most of the versions of this script across the web, it is essential for this to work interleaved with print statements
self.ipython_display()

def _ipython_display_(self):
    display(HTML('<div id="{}" style="height: auto; width:100%;"></div>'.format(self.uuid)))
    display(HTML("""<script>
    require(["https://rawgit.com/caldwell/renderjson/master/renderjson.js"], function() {
      renderjson.set_show_to_level(1)
      document.getElementById('%s').appendChild(renderjson(%s))
    });</script>
    """ % (self.uuid, self.json_str)))

RenderJSON(accounts[0])`

@john012343210
Copy link

having the same problem, i am solving

Came here from. I had some errors with datatime objects in my json, "TypeError: Object of type datetime is not JSON serializable". This was my fix for that problem thanks to.

`import uuid from IPython.core.display import display, HTML, JSON import json import datetime class DateTimeEncoder(json.JSONEncoder): def default(self, z): if isinstance(z, datetime.datetime): return (str(z)) else: return super().default(z)

class RenderJSON(object): def init(self, json_data): if isinstance(json_data, dict): self.json_str = json.dumps(json_data,cls=DateTimeEncoder) else: self.json_str = json_data self.uuid = str(uuid.uuid4()) # This line is missed out in most of the versions of this script across the web, it is essential for this to work interleaved with print statements self.ipython_display()

def _ipython_display_(self):
    display(HTML('<div id="{}" style="height: auto; width:100%;"></div>'.format(self.uuid)))
    display(HTML("""<script>
    require(["https://rawgit.com/caldwell/renderjson/master/renderjson.js"], function() {
      renderjson.set_show_to_level(1)
      document.getElementById('%s').appendChild(renderjson(%s))
    });</script>
    """ % (self.uuid, self.json_str)))

RenderJSON(accounts[0])`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment