如何在 Python 中漂亮地打印 JSON 文件?
最佳答案
使用 json.dump()
的 indent=
参数或 json.dumps()
指定要缩进多少个空格:
>>> import json
>>>
>>> your_json = '["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4))
[
"foo",
{
"bar": [
"baz",
null,
1.0,
2
]
}
]
要解析文件,请使用 json.load()
:
with open('filename.txt', 'r') as handle:
parsed = json.load(handle)
关于python - 如何漂亮地打印 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12943819/