如何打印JSON文件? [英] How to prettyprint a JSON file?

查看:277
本文介绍了如何打印JSON文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON文件,我想对其进行漂亮打印-在python中执行此操作最简单的方法是什么?我知道PrettyPrint带有一个对象",我认为它可以是一个文件,但我不知道如何传递文件-仅使用文件名是不起作用的.

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.

推荐答案

json模块已经使用indent参数实现了一些基本的漂亮打印:

The json module already implements some basic pretty printing with the indent parameter:

>>> 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
        ]
    }
]

要解析文件,请使用json.load():

with open('filename.txt', 'r') as handle:
    parsed = json.load(handle)

这篇关于如何打印JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆