Col*_*een 951 python json pretty-print
我有一个JSON文件是一个混乱,我想漂亮 - 在python中最简单的方法是什么?我知道PrettyPrint有一个"对象",我认为它可以是一个文件,但我不知道如何传入文件 - 只是使用文件名不起作用.
Ble*_*der 1484
该json模块已经使用indent参数实现了一些基本的漂亮打印:
>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4, sort_keys=True))
[
"foo",
{
"bar": [
"baz",
null,
1.0,
2
]
}
]
Run Code Online (Sandbox Code Playgroud)
要解析文件,请使用json.load():
with open('filename.txt', 'r') as handle:
parsed = json.load(handle)
Run Code Online (Sandbox Code Playgroud)
Gis*_*nas 294
您可以在命令行上执行此操作:
python3 -m json.tool < some.json
Run Code Online (Sandbox Code Playgroud)
(正如在问题的评论中已经提到的,感谢@Kai Petzke提出的python3建议).
实际上,就命令行上的json处理而言,python不是我最喜欢的工具.对于简单漂亮的打印是可以的,但如果你想操纵json它可能会变得过于复杂.你很快就需要编写一个单独的脚本文件,你最终可能会得到键是你的"某些键"(python unicode)的地图,这使得选择字段更加困难并且不会真正朝着漂亮的方向发展 - 印刷.
我用jq.以上可以通过以下方式完成:
jq . some.json
Run Code Online (Sandbox Code Playgroud)
并且您将颜色作为奖励(并且更容易扩展).
Shu*_*ary 48
Pygmentize是一种杀手级工具.看到这个.
我将python json.tool与pygmentize结合起来
echo '{"foo": "bar"}' | python -m json.tool | pygmentize -l json
Run Code Online (Sandbox Code Playgroud)
有关pygmentize安装说明,请参阅上面的链接.
这个演示如下图所示:
ikr*_*reb 48
您可以使用内置模块pprint.
如何使用json数据读取文件并将其打印出来.
import json
import pprint
with open('filename.txt', 'r') as f:
data = f.read()
json_data = json.loads(data)
pprint.pprint(json_data)
Run Code Online (Sandbox Code Playgroud)
zel*_*usp 34
使用这个功能,不要忘记你的JSON是一个str还是dict再次 - 只需看看漂亮的打印:
import json
def pp_json(json_thing, sort=True, indents=4):
if type(json_thing) is str:
print(json.dumps(json.loads(json_thing), sort_keys=sort, indent=indents))
else:
print(json.dumps(json_thing, sort_keys=sort, indent=indents))
return None
pp_json(your_json_string_or_dict)
Run Code Online (Sandbox Code Playgroud)
小智 11
为了能够从命令行进行漂亮的打印并能够控制缩进等,您可以设置类似于此的别名:
alias jsonpp="python -c 'import sys, json; print json.dumps(json.load(sys.stdin), sort_keys=True, indent=2)'"
Run Code Online (Sandbox Code Playgroud)
然后以下列方式之一使用别名:
cat myfile.json | jsonpp
jsonpp < myfile.json
Run Code Online (Sandbox Code Playgroud)
使用pprint:https ://docs.python.org/3.6/library/pprint.html
import pprint
pprint.pprint(json)
Run Code Online (Sandbox Code Playgroud)
print() 相比 pprint.pprint()
print(json)
{'feed': {'title': 'W3Schools Home Page', 'title_detail': {'type': 'text/plain', 'language': None, 'base': '', 'value': 'W3Schools Home Page'}, 'links': [{'rel': 'alternate', 'type': 'text/html', 'href': 'https://www.w3schools.com'}], 'link': 'https://www.w3schools.com', 'subtitle': 'Free web building tutorials', 'subtitle_detail': {'type': 'text/html', 'language': None, 'base': '', 'value': 'Free web building tutorials'}}, 'entries': [], 'bozo': 0, 'encoding': 'utf-8', 'version': 'rss20', 'namespaces': {}}
pprint.pprint(json)
{'bozo': 0,
'encoding': 'utf-8',
'entries': [],
'feed': {'link': 'https://www.w3schools.com',
'links': [{'href': 'https://www.w3schools.com',
'rel': 'alternate',
'type': 'text/html'}],
'subtitle': 'Free web building tutorials',
'subtitle_detail': {'base': '',
'language': None,
'type': 'text/html',
'value': 'Free web building tutorials'},
'title': 'W3Schools Home Page',
'title_detail': {'base': '',
'language': None,
'type': 'text/plain',
'value': 'W3Schools Home Page'}},
'namespaces': {},
'version': 'rss20'}
Run Code Online (Sandbox Code Playgroud)
我曾经写过一个prettyjson()函数来产生漂亮的输出。您可以从此仓库中获取实现。
此功能的主要功能是尝试将dict和list项目保留在一行中,直到maxlinelength达到确定值为止。这样会产生更少的JSON行,输出看起来更紧凑且更易于阅读。
您可以产生这种输出,例如:
{
"grid": {"port": "COM5"},
"policy": {
"movingaverage": 5,
"hysteresis": 5,
"fan1": {
"name": "CPU",
"signal": "cpu",
"mode": "auto",
"speed": 100,
"curve": [[0, 75], [50, 75], [75, 100]]
}
}
Run Code Online (Sandbox Code Playgroud)
TL;DR:方法很多,也可以考虑print(yaml.dump(j, sort_keys=False))
对于大多数用途,缩进应该做到这一点:
\nprint(json.dumps(parsed, indent=2))\nRun Code Online (Sandbox Code Playgroud)\nJson 结构基本上是树结构。\n在尝试寻找更奇特的东西时,我发现了这篇不错的论文,描述了可能有趣的其他形式的漂亮树:https: //blog.ouseful.info/2021/07/13/exploring -dataframes-and-csv-data/ 的层次结构。
\n它有一些交互式树,甚至附带了一些代码,包括来自以下的折叠树:\n
其他示例包括使用plotly以下是plotly 的代码示例:
\nimport plotly.express as px\nfig = px.treemap(\n names = ["Eve","Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"],\n parents = ["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve"]\n)\nfig.update_traces(root_color="lightgrey")\nfig.update_layout(margin = dict(t=50, l=25, r=25, b=25))\nfig.show()\nRun Code Online (Sandbox Code Playgroud)\n\n并使用treelib。在这一点上,这个 github还提供了很好的可视化效果。下面是一个使用 treelib 的示例:
\n#%pip install treelib\nfrom treelib import Tree\n\ncountry_tree = Tree()\n# Create a root node\ncountry_tree.create_node("Country", "countries")\n\n# Group by country\nfor country, regions in wards_df.head(5).groupby(["CTRY17NM", "CTRY17CD"]):\n # Generate a node for each country\n country_tree.create_node(country[0], country[1], parent="countries")\n # Group by region\n for region, las in regions.groupby(["GOR10NM", "GOR10CD"]):\n # Generate a node for each region\n country_tree.create_node(region[0], region[1], parent=country[1])\n # Group by local authority\n for la, wards in las.groupby([\'LAD17NM\', \'LAD17CD\']):\n # Create a node for each local authority\n country_tree.create_node(la[0], la[1], parent=region[1])\n for ward, _ in wards.groupby([\'WD17NM\', \'WD17CD\']):\n # Create a leaf node for each ward\n country_tree.create_node(ward[0], ward[1], parent=la[1])\n\n# Output the hierarchical data\ncountry_tree.show()\nRun Code Online (Sandbox Code Playgroud)\n\n基于此,我创建了一个将 json 转换为树的函数:
\nfrom treelib import Node, Tree, node\n\ndef create_node(tree, s, counter_byref, verbose, parent_id=None):\n node_id = counter_byref[0]\n if verbose:\n print(f"tree.create_node({s}, {node_id}, parent={parent_id})")\n tree.create_node(s, node_id, parent=parent_id)\n counter_byref[0] += 1\n return node_id\n\ndef to_compact_string(o):\n if type(o) == dict:\n if len(o)>1:\n raise Exception()\n k,v =next(iter(o.items()))\n return f\'{k}:{to_compact_string(v)}\'\n elif type(o) == list:\n if len(o)>1:\n raise Exception()\n return f\'[{to_compact_string(next(iter(o)))}]\'\n else:\n return str(o)\n\ndef to_compact(tree, o, counter_byref, verbose, parent_id):\n try:\n s = to_compact_string(o)\n if verbose:\n print(f"# to_compact({o}) ==> [{s}]")\n create_node(tree, s, counter_byref, verbose, parent_id=parent_id)\n return True\n except:\n return False\n\ndef json_2_tree(o , parent_id=None, tree=None, counter_byref=[0], verbose=False, compact_single_dict=False, listsNodeSymbol=\'+\'):\n if tree is None:\n tree = Tree()\n parent_id = create_node(tree, \'+\', counter_byref, verbose)\n if compact_single_dict and to_compact(tree, o, counter_byref, verbose, parent_id):\n # no need to do more, inserted as a single node\n pass\n elif type(o) == dict:\n for k,v in o.items():\n if compact_single_dict and to_compact(tree, {k:v}, counter_byref, verbose, parent_id):\n # no need to do more, inserted as a single node\n continue\n key_nd_id = create_node(tree, str(k), counter_byref, verbose, parent_id=parent_id)\n if verbose:\n print(f"# json_2_tree({v})")\n json_2_tree(v , parent_id=key_nd_id, tree=tree, counter_byref=counter_byref, verbose=verbose, listsNodeSymbol=listsNodeSymbol, compact_single_dict=compact_single_dict)\n elif type(o) == list:\n if listsNodeSymbol is not None:\n parent_id = create_node(tree, listsNodeSymbol, counter_byref, verbose, parent_id=parent_id)\n for i in o:\n if compact_single_dict and to_compact(tree, i, counter_byref, verbose, parent_id):\n # no need to do more, inserted as a single node\n continue\n if verbose:\n print(f"# json_2_tree({i})")\n json_2_tree(i , parent_id=parent_id, tree=tree, counter_byref=counter_byref, verbose=verbose,listsNodeSymbol=listsNodeSymbol, compact_single_dict=compact_single_dict)\n else: #node\n create_node(tree, str(o), counter_byref, verbose, parent_id=parent_id)\n return tree\nRun Code Online (Sandbox Code Playgroud)\n那么例如:
\nimport json\nj = json.loads(\'{"2": 3, "4": [5, 6], "7": {"8": 9}}\')\njson_2_tree(j ,verbose=False,listsNodeSymbol=\'+\' ).show() \nRun Code Online (Sandbox Code Playgroud)\n给出:
\n+\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 2\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 3\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 4\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 +\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 5\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 6\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 7\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 8\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 9\nRun Code Online (Sandbox Code Playgroud)\n尽管
\njson_2_tree(j ,listsNodeSymbol=None, verbose=False ).show() \nRun Code Online (Sandbox Code Playgroud)\n+\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 2\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 3\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 4\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 5\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 6\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 7\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 8\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 9\nRun Code Online (Sandbox Code Playgroud)\n和
\njson_2_tree(j ,compact_single_dict=True,listsNodeSymbol=None).show() \nRun Code Online (Sandbox Code Playgroud)\n+\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 2:3\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 4\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 5\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 6\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 7:8:9\nRun Code Online (Sandbox Code Playgroud)\n正如您所看到的,根据他想要的明确程度和紧凑程度,可以制作不同的树。\n我最喜欢的树之一,也是最紧凑的树之一可能是使用yaml:
\nimport yaml\nj = json.loads(\'{"2": "3", "4": ["5", "6"], "7": {"8": "9"}}\')\nprint(yaml.dump(j, sort_keys=False))\nRun Code Online (Sandbox Code Playgroud)\n给出紧凑且明确的:
\n\'2\': \'3\'\n\'4\':\n- \'5\'\n- \'6\'\n\'7\':\n \'8\': \'9\'\nRun Code Online (Sandbox Code Playgroud)\n
小智 7
def saveJson(date,fileToSave):
with open(fileToSave, 'w+') as fileToSave:
json.dump(date, fileToSave, ensure_ascii=True, indent=4, sort_keys=True)
Run Code Online (Sandbox Code Playgroud)
它可以将其显示或保存到文件中。
一个非常简单的方法是使用 rich。通过这种方法,您还可以突出显示json
该方法从名为的 json 文件读取数据config.json
from rich import print_json
setup_type = open('config.json')
data = json.load(setup_type)
print_json(data=data)
Run Code Online (Sandbox Code Playgroud)
你可以试试pprintjson。
$ pip3 install pprintjson
Run Code Online (Sandbox Code Playgroud)
使用 pprintjson CLI 从文件漂亮地打印 JSON。
$ pprintjson "./path/to/file.json"
Run Code Online (Sandbox Code Playgroud)
使用 pprintjson CLI 从标准输入漂亮地打印 JSON。
$ echo '{ "a": 1, "b": "string", "c": true }' | pprintjson
Run Code Online (Sandbox Code Playgroud)
使用 pprintjson CLI 从字符串漂亮地打印 JSON。
$ pprintjson -c '{ "a": 1, "b": "string", "c": true }'
Run Code Online (Sandbox Code Playgroud)
从缩进为 1 的字符串中漂亮地打印 JSON。
$ pprintjson -c '{ "a": 1, "b": "string", "c": true }' -i 1
Run Code Online (Sandbox Code Playgroud)
从字符串漂亮地打印 JSON 并将输出保存到文件 output.json。
$ pprintjson -c '{ "a": 1, "b": "string", "c": true }' -o ./output.json
Run Code Online (Sandbox Code Playgroud)
小智 5
这是一个简单的示例,该示例以很好的方式在Python中将JSON打印到控制台,而无需将JSON作为本地文件存储在计算机上:
import pprint
import json
from urllib.request import urlopen # (Only used to get this example)
# Getting a JSON example for this example
r = urlopen("https://mdn.github.io/fetch-examples/fetch-json/products.json")
text = r.read()
# To print it
pprint.pprint(json.loads(text))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
893705 次 |
| 最近记录: |