IPython Noteb中漂亮的JSON格式

2024-04-18 19:52:18 发布

您现在位置:Python中文网/ 问答频道 /正文

在ipython笔记本中,有没有一种现有的方法可以让json.dumps()输出显示为“漂亮”格式的JSON?


Tags: 方法json格式ipython笔记本dumps
3条回答

json.dumps有一个indent参数,打印结果就足够了:

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

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

from IPython.display import JSON
JSON({'a': [1, 2, 3, 4,], 'b': {'inner1': 'helloworld', 'inner2': 'foobar'}})

编辑:这项工作在氢和朱庇特实验室,但不在朱庇特笔记本或在IPython终端。

内部Hydrogen

enter image description hereenter image description here

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)

要以可折叠格式输出数据,请执行以下操作:

RenderJSON(your_json)

从这里粘贴的副本:https://www.reddit.com/r/IPython/comments/34t4m7/lpt_print_json_in_collapsible_format_in_ipython/

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

相关问题 更多 >