IPython Notebook中漂亮的JSON格式

plupiseo  于 2022-12-05  发布在  Python
关注(0)|答案(8)|浏览(191)

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

kgqe7b3p

kgqe7b3p1#

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

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

p1iqtdky2#

这可能与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
第一次

thigvfpy

thigvfpy3#

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

aor9mmx1

aor9mmx14#

我只是将扩展变量添加到@凯尔巴伦回答中:

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

0vvn1miw5#

我发现这个页面在寻找一种方法来消除输出中的文字\n s。我们正在使用Jupyter做一个编码采访,我想要一种方法来显示一个函数的结果 * 真实的perty like*。我的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

我希望这能帮助到一些人!

brgchamk

brgchamk6#

对于Jupyter笔记本来说,可能就足以生成链接以在新标签页中打开(用Firefox的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

jutyujz0

jutyujz07#

只是@filmor answer(https://stackoverflow.com/a/18873131/7018342)的扩展名。
这对可能与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
}
dzjeubhm

dzjeubhm8#

对于某些用途,缩进应使其:

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

一个Json结构基本上是tree structure。当我试图找到一些更花哨的东西时,我看到了这篇描述其他形式的漂亮树的文章,这可能是有趣的:是的。
它有一些交互式的树,甚至带有一些代码,包括链接到这个问题和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()

第一次
使用treelib。在这一点上,This github也提供了很好的可视化。下面是一个使用树库的示例:

#%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()

基于此,我创建了一个函数来将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

相关问题