IPython Notebook 中漂亮的 JSON 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18873066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:08:32  来源:igfitidea点击:

Pretty JSON Formatting in IPython Notebook

pythonjsonipython-notebook

提问by Kyle Brandt

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

是否有现有的方法可以让json.dumps()输出在 ipython notebook 中显示为“漂亮”格式的 JSON?

采纳答案by filmor

json.dumpshas an indentargument, printing the result should be enough:

json.dumps有一个indent论点,打印结果应该就足够了:

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

回答by John Carrell

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 notthe best way to do it but...)

我发现这个页面正在寻找一种方法来消除\n输出中的文字s。我们正在使用 Jupyter 进行编码面试,我想要一种方法来显示. 我的 Jupyter (4.1.0) 版本不会将它们呈现为实际的换行符。我产生的解决方案是(我有点希望这不是最好的方法,但是......)

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!

我希望这可以帮助别人!

回答by Shankar ARUL - jupyterdata.com

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/

从这里复制粘贴:https: //www.reddit.com/r/IPython/comments/34t4m7/lpt_print_json_in_collapsible_format_in_ipython/

Github: https://github.com/caldwell/renderjson

Github:https: //github.com/caldwell/renderjson

回答by Kyle Barron

This might be slightly different than what OP was asking for, but you can do use IPython.display.JSONto interactively view a JSON/dictobject.

这可能与 OP 要求的略有不同,但您可以使用IPython.display.JSON交互式查看 JSON/dict对象。

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.

编辑:这适用于 Hydrogen 和 JupyterLab,但不适用于 Jupyter Notebook 或 IPython 终端。

Inside Hydrogen:

氢气内部:

enter image description hereenter image description here

在此处输入图片说明在此处输入图片说明

回答by Joe Cabezas

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

我只是将扩展变量添加到@Kyle Barron 答案中:

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