在 Python 中漂亮地打印 JSON 文件
分析或操作 JSON 数据时,将其格式化为人类格式通常会很有帮助- 更容易查看的可读方式。
漂亮的打印JSON
要在 Python 中漂亮地打印 JSON 文件,请利用 json.dump() 或 json.dumps 的 indent 参数() 函数。在 indent 参数中指定所需的缩进空格数。
例如:
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 ] } ]
在此例如,indent 参数设置为 4,导致 JSON 缩进为 4
漂亮打印 JSON 文件
要漂亮打印 JSON 文件,您可以使用 json.load()函数:
with open('filename.txt', 'r') as handle: parsed = json.load(handle)
这会将 JSON 文件加载到 parsed 中变量,然后可以使用 json.dumps() 函数进行漂亮的打印,如上所示。
以上是如何在 Python 中漂亮打印 JSON 文件?的详细内容。更多信息请关注PHP中文网其他相关文章!