Pretty JSON Formatting in IPython Notebook

六眼飞鱼酱① 提交于 2020-11-30 04:18:47

问题


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


回答1:


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

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



回答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:




回答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




回答4:


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!




回答5:


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

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


来源:https://stackoverflow.com/questions/18873066/pretty-json-formatting-in-ipython-notebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!