如何用Python打印JSON文件?


当前回答

这里有一个简单的例子,可以用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))

其他回答

使用json.dump()或json.dumps()的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
        ]
    }
]

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

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

这远不是完美的,但它确实起到了作用。

data = data.replace(',"',',\n"')

你可以改进它,添加缩进等等,但是如果你只是想读一个更干净的json,这就是方法。

您可以尝试pprintjson。


安装

$ pip3 install pprintjson

用法

使用pprintjson CLI从文件中精确打印JSON。

$ pprintjson "./path/to/file.json"

使用pprintjson CLI从stdin打印JSON。

$ echo '{ "a": 1, "b": "string", "c": true }' | pprintjson

使用pprintjson CLI从字符串中精确打印JSON。

$ pprintjson -c '{ "a": 1, "b": "string", "c": true }'

从缩进为1的字符串中精确打印JSON。

$ pprintjson -c '{ "a": 1, "b": "string", "c": true }' -i 1

从字符串中精确打印JSON并将输出保存到文件output.JSON。

$ pprintjson -c '{ "a": 1, "b": "string", "c": true }' -o ./output.json

输出

您可以在命令行上执行此操作:

python3 -m json.tool some.json

(正如问题评论中已经提到的,感谢@Kai Petzke提出的蟒蛇3建议)。

实际上,就命令行上的json处理而言,python不是我最喜欢的工具。对于简单漂亮的打印是可以的,但是如果你想操作json,它可能会变得过于复杂。您很快就需要编写一个单独的脚本文件,最终可能会得到键为u“somekey”(python unicode)的映射,这使得选择字段变得更加困难,并不会真正朝着漂亮打印的方向发展。

您也可以使用jq:

jq . some.json

你可以得到颜色作为奖励(而且更容易扩展)。

附录:关于一方面使用jq处理大型JSON文件,另一方面使用非常大的jq程序,评论中存在一些困惑。对于漂亮地打印由单个大型JSON实体组成的文件,实际限制是RAM。对于由单个真实世界数据数组组成的2GB文件的漂亮打印,漂亮打印所需的“最大驻留集大小”为5GB(无论使用jq 1.5还是1.6)。还要注意,在pip安装jq之后,可以在python中使用jq。

我认为最好先解析json,以避免错误:

def format_response(response):
    try:
        parsed = json.loads(response.text)
    except JSONDecodeError:
        return response.text
    return json.dumps(parsed, ensure_ascii=True, indent=4)