如何漂亮地打印 JSON 文件? [英] How to prettyprint a JSON file?
本文介绍了如何漂亮地打印 JSON 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个乱七八糟的 JSON 文件,我想打印出来.在 Python 中执行此操作的最简单方法是什么?
我知道 PrettyPrint 接受一个对象",我认为它可以是一个文件,但我不知道如何传入文件.仅使用文件名是行不通的.
解决方案
json
模块已经使用 indent
参数实现了一些基本的漂亮打印,该参数指定了多少空格缩进:
要解析文件,请使用 json.load()
:
with open('filename.txt', 'r') 作为句柄:解析 = json.load(handle)
I have a JSON file that is a mess that I want to prettyprint. What's the easiest way to do this in Python?
I know PrettyPrint takes an "object", which I think can be a file, but I don't know how to pass a file in. Just using the filename doesn't work.
解决方案
The json
module already implements some basic pretty printing with the indent
parameter that specifies how many spaces to indent by:
>>> 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
]
}
]
To parse a file, use json.load()
:
with open('filename.txt', 'r') as handle:
parsed = json.load(handle)
这篇关于如何漂亮地打印 JSON 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文