IPython Notebook中漂亮的JSON格式化

78

有没有现成的方法可以使json.dumps()输出以漂亮的格式显示为JSON在ipython笔记本中?


最简单的方法是使用 pprint() 来打印JSON (from pprint import pprint)。 - PeJota
8个回答

118

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

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

11
输出中的颜色怎么样? - ganqqwerty
把以下與編程相關的內容從英文翻譯成中文。只返回已翻譯的文本:然而,使用這種方法造成了Unicode字符混亂。 - Luk Aron
1
这简直不是事实。Python的json.dumps默认为ensure_ascii=True,这会转义中文(或者说:任何非ASCII)字符。使用print(json.dumps(obj, indent=2, ensure_ascii=False)),你就可以得到未转义的字符了。 - filmor

90

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

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

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

Hydrogen 中:

输入图像描述 输入图像描述


2
我从来没有这么开心过! - Diptangsu Goswami
3
这让我感到困惑,因为这在 Jupyter Lab 中可以运行,但在传统的笔记本中却不行。在那里,如果存在 repr_json 方法,则会调用它。 - marscher

41
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


我无法在Jupyter 1.0上使其工作。有任何想法吗?Javascript控制台显示:“SyntaxError:Unexpected token <”。 - Pierre Carbonnelle
代码存在问题。第10行应更改为self.json_str = json_data。这解决了@user474491报告的问题。 - Hassan
1
我已经更新了一些问题,并在最新的Jupyter Notebook中使其工作,包括@user474491和@Hassan的建议,我还在__init __()中添加了一个显式调用_ipython_display_(),以确保我们可以安全地交错调用python的本机print()RenderJSON(),并仍然使其工作。 https://gist.github.com/t27/48b3ac73a1479914f9fe9383e5d45325 - Tarang Shah
1
我刚刚收到了“Javascript错误:未定义require”的提示。 - andy
我遇到了一个可能与@andy类似的错误,但它显示“Javascript错误:找不到变量:require”。 - Danny Kaufman
显示剩余2条评论

8

我只是在 @Kyle Barron 的回答中添加了扩展变量:

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

3
对我来说它不起作用。TypeError: __init __()收到了一个意外的关键字参数“expanded”。 - mrvol
这对我来说很好用。使用“expanded”关键字时没有错误。我的IPython.__version__显示为“7.8.0”。 - David
5
对我来说没有错误,但我得到的输出是<IPython.core.display.JSON object>,没有交互式漂亮打印。 - ShnitzelKiller
我有同样的问题,你能解决吗? - Bob van Luijt
@ShnitzelKiller,你可能会使用print(JSON(...))来打印它。 - undefined
@blogbydev 不对。我也有一样的问题。只是这个一行的JSON({...})被显示为<IPython.core.display.JSON object> - undefined

4
我发现这个页面是为了寻找一种消除输出中字面上的\n的方法。我们正在使用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

希望这能帮助到某些人!


0

这只是对@filmor答案(https://dev59.com/yWMk5IYBdhLWcg3w5R2k#18873131)的一个扩展。

它编码了一些可能与json.dumps不兼容的元素,并提供了一个方便的函数,可以像使用print一样使用它。

import json
class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        if isinstance(obj, np.floating):
            return float(obj)
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        if isinstance(obj, np.bool_):
            return bool(obj)
        return super(NpEncoder, self).default(obj)

def print_json(json_dict):
    print(json.dumps(json_dict, indent=2, cls=NpEncoder))

使用方法:

json_dict = {"Name":{"First Name": "Lorem", "Last Name": "Ipsum"}, "Age":26}
print_json(json_dict)
>>>
{
  "Name": {
    "First Name": "Lorem",
    "Last Name": "Ipsum"
  },
  "Age": 26
}

0

对于某些用途,缩进应该这样做:

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

一个Json结构基本上就是树形结构。 在尝试寻找更加花哨的东西时,我发现了这篇很好的论文,其中描述了其他形式的漂亮树形结构,可能会很有趣:https://blog.ouseful.info/2021/07/13/exploring-the-hierarchical-structure-of-dataframes-and-csv-data/

它包含一些交互式树形结构,甚至还附带了一些代码,包括链接到这个问题和来自Shankar ARUL的可折叠树形结构。

其他示例包括使用plotly。以下是来自plotly的代码示例:

import plotly.express as px
fig = px.treemap(
    names = ["Eve","Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"],
    parents = ["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve"]
)
fig.update_traces(root_color="lightgrey")
fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
fig.show()

enter image description here enter image description here

并使用treelib。另外,这个github也提供了很好的可视化效果。以下是一个使用treelib的示例:

#%pip install treelib
from treelib import Tree

country_tree = Tree()
# Create a root node
country_tree.create_node("Country", "countries")

# Group by country
for country, regions in wards_df.head(5).groupby(["CTRY17NM", "CTRY17CD"]):
    # Generate a node for each country
    country_tree.create_node(country[0], country[1], parent="countries")
    # Group by region
    for region, las in regions.groupby(["GOR10NM", "GOR10CD"]):
        # Generate a node for each region
        country_tree.create_node(region[0], region[1], parent=country[1])
        # Group by local authority
        for la, wards in las.groupby(['LAD17NM', 'LAD17CD']):
            # Create a node for each local authority
            country_tree.create_node(la[0], la[1], parent=region[1])
            for ward, _ in wards.groupby(['WD17NM', 'WD17CD']):
                # Create a leaf node for each ward
                country_tree.create_node(ward[0], ward[1], parent=la[1])

# Output the hierarchical data
country_tree.show()

enter image description here

基于此,我创建了一个将JSON转换为树形结构的函数:

from treelib import Node, Tree, node
def json_2_tree(o , parent_id=None, tree=None, counter_byref=[0], verbose=False, listsNodeSymbol='+'):
    if tree is None:
        tree = Tree()
        root_id = counter_byref[0]
        if verbose:
            print(f"tree.create_node({'+'}, {root_id})")
        tree.create_node('+', root_id)
        counter_byref[0] += 1
        parent_id = root_id
    if type(o) == dict:
        for k,v in o.items():
            this_id = counter_byref[0]
            if verbose:
                print(f"tree.create_node({str(k)}, {this_id}, parent={parent_id})")
            tree.create_node(str(k), this_id, parent=parent_id)
            counter_byref[0]  += 1
            json_2_tree(v , parent_id=this_id, tree=tree, counter_byref=counter_byref, verbose=verbose, listsNodeSymbol=listsNodeSymbol)
    elif type(o) == list:
        if listsNodeSymbol is not None:
            if verbose:
                print(f"tree.create_node({listsNodeSymbol}, {counter_byref[0]}, parent={parent_id})")
            tree.create_node(listsNodeSymbol, counter_byref[0], parent=parent_id)
            parent_id=counter_byref[0]
            counter_byref[0]  += 1        
        for i in o:
            json_2_tree(i , parent_id=parent_id, tree=tree, counter_byref=counter_byref, verbose=verbose,listsNodeSymbol=listsNodeSymbol)
    else: #node
        if verbose:
            print(f"tree.create_node({str(o)}, {counter_byref[0]}, parent={parent_id})")
        tree.create_node(str(o), counter_byref[0], parent=parent_id)
        counter_byref[0] += 1
    return tree

例如:

import json
json_2_tree(json.loads('{"2": 3, "4": [5, 6]}'),verbose=False,listsNodeSymbol='+').show()       

提供:

+
├── 2
│   └── 3
└── 4
    └── +
        ├── 5
        └── 6

json_2_tree(json.loads('{"2": 3, "4": [5, 6]}'),listsNodeSymbol=None).show()       

提供

+
├── 2
│   └── 3
└── 4
    ├── 5
    └── 6

正如您所看到的,根据一个人想要多么明确或紧凑,他可以制作不同的树形结构。 我最喜欢的之一,也是最紧凑的之一,可能是使用yaml

import yaml
j = json.loads('{"2": "3", "4": ["5", "6"], "7": {"8": "9"}}')
print(yaml.dump(j, sort_keys=False))

提供简洁明了的内容:
'2': '3'
'4':
- '5'
- '6'
'7':
  '8': '9'

0
对于Jupyter笔记本,可能只需生成链接以在新标签页中打开(使用火狐浏览器的JSON查看器)即可:
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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接